在python中创建一个子进程,并在超时后退出
我是python新手,因此无法在以下场景中创建python脚本:在python中创建一个子进程,并在超时后退出,python,python-2.7,Python,Python 2.7,我是python新手,因此无法在以下场景中创建python脚本: 1. Run a sub process. 2. Need to check in every 5 sec a file stop.txt is exit then 3. Stop the subrocess and exit from the script. 4. If not exit the stop.txt. then need to continue the sub process. 感谢adv.中提供的通过终端运行的
1. Run a sub process.
2. Need to check in every 5 sec a file stop.txt is exit then
3. Stop the subrocess and exit from the script.
4. If not exit the stop.txt. then need to continue the sub process.
感谢adv.中提供的通过终端运行的流程,请查看模块。要等待5秒钟,请使用模块。等待后,您可以在读取模式下打开文件,然后读取,直到找到“退出”。一个简单的例子:
import subproccess, time
background_task = subproccess.Popen(background_task)
while 1:
time.sleep(5)
with open('background_task.txt', 'r') as task_file:
if task_file.read() == 'exit':
background_task.kill()
exit()
最好的方法是在子流程中处理。否则您将不得不从父进程调用
.kill
。@freakish:我只有一个子进程p=subprocess.Popen(),如何在一段时间后终止。