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

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

  •  17-07-2023
  •  | 
  •  

Pregunta

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.

¿Fue útil?

Solución

Use subprocess.

import subprocess
import time

p = subprocess.Popen(['notepad.exe'])
time.sleep(10)
p.kill()
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top