Starting a new process from python script and then killing it from the same script

StackOverflow https://stackoverflow.com/questions/23535377

  •  17-07-2023
  •  | 
  •  

سؤال

I have looked at python's subprocess and os modules but have not been able to find a concrete example. Here is an example of what I want to do:

os.system(r"someprocess.exe")
time.sleep(10)
os.system(r"TASKKILL /F /IM someprocess.exe")

Currently after running the first line, the shell runs the process within it, and does not move forward. On the other hand, I want it to spawn a new process independent of this python shell, go to sleep, and then kill it after sometime. I am on a windows machine.

هل كانت مفيدة؟

المحلول

Use subprocess.

import subprocess
import time

p = subprocess.Popen(['notepad.exe'])
time.sleep(10)
p.kill()
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top