I am writing a code but it has not worked as expected. A simplified version of the code is as follows:
from subprocess import call
import time
call([r"C:\Windows\System32\notepad.exe"])
time.sleep(5)
call(["taskkill", "/im", "notepad.exe"])
When running the script above, the code does not run from the first line call
, that is, the script opens the notepad and waits for a response from call([r"C:\Windows\System32\notepad.exe"])
, but this only happens when I manually close the notepad.
I would like the script to open the notepad, wait 5 seconds and close it, without manual user intervention. So how can I do it?
What you can do is use
Popen
instead ofcall
:The subprocess.call function waits for the command to complete, which is why it returns execution control to you when you close the
notepad.exe
.The subprocess.Popen function is executed in a new (child) process.
After the
sleep
, you can use the functionPopen.kill
to terminate the process:If you want to interact with the thread using
Popen
(send data tostdin
, read fromstdout
orstderr
), you can use the functionPopen.communicate
:But note that it
Popen.communicate
waits for thread completion, so there is no need to usePopen.kill