baw*_*uju 0 python linux flask
我有一个使用 python3 的 Flask 应用程序。有时它会创建守护进程来运行脚本,然后我想在超时时杀死守护进程(使用signal.SIGINT)。
但是,一些由os.system(例如,os.system('git clone xxx'))创建的进程在守护进程被杀死后仍在运行。所以我该怎么做?谢谢大家!
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")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9511 次 |
| 最近记录: |