linux - Bash: Waiting on a background python process -




i'm trying to:

  1. launch background process (a python script)
  2. run bash commands
  3. 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

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -