Skip to content

Instantly share code, notes, and snippets.

@kbakk
Last active October 26, 2021 12:40
Show Gist options
  • Save kbakk/d14fcf727783fec4b306b5db148b9ec3 to your computer and use it in GitHub Desktop.
Save kbakk/d14fcf727783fec4b306b5db148b9ec3 to your computer and use it in GitHub Desktop.
Cancelling subprocess - getting proper return code

Manually (ctrl+c) cancelling

python child.py
Sleeping
.
.
.
.
^CReceived 2 , exiting 10

Cancelling from parent and subprocess.Popen.send_signal

$ python parent.py
Sleeping
.
.
Sending SIGINT to child
Received 2 , exiting 10
Child exited with 10
# will sleep 10 sec and exit with code 0, unless it receives SIGINT (ctrl+c),
# in that case it exits with code 10
import signal, sys, time
def signal_handler(sig, frame):
print('Received', sig, ", exiting 10")
sys.exit(10)
signal.signal(signal.SIGINT, signal_handler)
print("Sleeping ")
for _ in range(10):
print(".")
time.sleep(1)
print("Didn't receive signal, exiting 0")
sys.exit(0)
import signal, subprocess, sys, time
proc = subprocess.Popen([sys.executable, "child.py"])
time.sleep(2)
print("Sending SIGINT to child")
proc.send_signal(signal.SIGINT)
proc.wait()
print("Child exited with", proc.returncode)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment