I have a Flask application using python3. Sometimes it create daemon process to run script, then I want to kill daemon when timeout (use signal.SIGINT
).
However, some processes which created by os.system
(for example, os.system('git clone xxx')
) are still running after daemon was killed.
so what should I do? Thanks all!
In order to be able to kill a process you need its process id (usually referred to as a pid). os.system
doesn't give you that, simply returning the value of the subprocess's return code.
The newer subprocess
module gives you much more control, at the expense of somewhat more complexity. In particular it allows you to wait for the process to finish, with a timeout if required, and gives you access to the subprocess's pid. While I am not an expert in its use, this seems to
work. Note that this code needs Python 3.3 or better to use the timeout
argument to the Popen.wait
call.
import subprocess
process = subprocess.Popen(['git', 'clone', 'https://github.com/username/reponame'])
try:
print('Running in process', process.pid)
process.wait(timeout=10)
except subprocess.TimeoutExpired:
print('Timed out - killing', process.pid)
process.kill()
print("Done")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With