简体   繁体   中英

Execute a shell script with ampersand from a python program

I want to submit my long running Python job using ampersand. I'm going to kick this process off from an interactive Python program by using a sub process call it.

How would I keep track of the submitted job programmatically in case I want to end the job from a menu option?

Example of interactive program:
Main Menu
1. Submit long running job &
2. End long running job

If you're using python's subprocess module, you don't really need to background it again with & do you? You can just keep your Popen object around to track the job, and it will run while the other python process continues.

If your "outer" python process is going to terminate what sort of track do you need to keep? Would pgrep / pkill be suitable? Alternately, you could have the long running job log its PID, often under /var/run somewhere, and use that to track if the process is still alive and/or signal it.

You could use Unix signals. Here we capture SIGUSR1 to tell the process to communicate some info to STDOUT .

#!/usr/bin/env python
import signal
import sys
def signal_handler(signal, frame):
    print('Caught SIGUSR1!')
    print("Current job status is " + get_job_status())

signal.signal(signal.SIGUSR1, signal_handler)

and then from the shell

kill <pid> --signal SIGUSR1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM