4

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 execution

p = subprocess.call(cmd)

So I cant use os.kill to kill that. Also, can't use shell=True because reasons.

What I would like to do is :

try:
  p = subprocess.call(cmd)
except KeyboardInterrupt:
  os.kill(p.pid,signal.SIGTERM)
  sys.exit('exited after ctrl-c')
Abhijeet Kale
  • 1,656
  • 1
  • 16
  • 34
anujdeshpande
  • 313
  • 1
  • 5
  • 11

1 Answers1

12
  1. p is just an integer (.returncode) and therefore there is no .pid attribute (run your code, press CTRL+C and see what happens)

  2. 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()
Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670