linux - Bash: Waiting on a background python process -
this question has answer here:
i'm trying to:
- launch background process (a python script)
- run bash commands
- then send control-c shut down background process once foreground tasks finished
minimal example of i've tried - python test.py
:
import sys try: print("running") while true: pass except keyboardinterrupt: print("escape!")
bash test.sh
:
#!/bin/bash python3 ./test.py & pid=$! # ... here ... sleep 2 # send interrupt background process # , wait finish cleanly echo "shutdown" kill -sigint $pid wait result=$? echo $result exit $result
but bash script seems hanging on wait , sigint signal not being sent python process.
i'm using mac os x, , looking solution works bash on linux + mac.
edit: bash sending interrupts python not capturing them when being run background job. fixed adding following python script:
import signal signal.signal(signal.sigint, signal.default_int_handler)
the point sigint
used terminate foreground process. should directly use kill $pid
terminate background process.
btw, kill $pid
equal kill -15 $pid
or kill -sigterm $pid
.
update
you can use signal
module deal situation.
import signal import sys def handle(signum, frame): sys.exit(0) signal.signal(signal.sigint, handle) print("running") while true: pass
wiki
Comments
Post a Comment