Kill Subprocess.call After Keyboardinterrupt
I need to stop a process created using subprocess.call in Python when I get a Keyboard Interrupt (ctrl-c) The issue is p doesn't get a value assigned to it till it finishes executi
Solution 1:
p
is just an integer (.returncode
) and therefore there is no.pid
attribute (run your code, press CTRL+C and see what happens)On POSIX,
SIGINT
is sent to the foreground process group of the terminal and therefore the child should be killed without any additional actions on your part, see How CTRL+C works You can check whether the child is terminated on Windows too.
If the child were not killed on KeyboardInterrupt
then you could do it manually: subprocess.call()
is just Popen().wait()
-- you could call it yourself:
p = subprocess.Popen(cmd)
try:
p.wait()
except KeyboardInterrupt:
try:
p.terminate()
except OSError:
pass
p.wait()
Post a Comment for "Kill Subprocess.call After Keyboardinterrupt"