Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill process which created by python os.system()

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!

like image 549
bawuju Avatar asked Sep 11 '25 19:09

bawuju


1 Answers

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")
like image 54
holdenweb Avatar answered Sep 14 '25 13:09

holdenweb