Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中创建一个子进程,并在超时后退出_Python_Python 2.7 - Fatal编程技术网

在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.中提供的通过终端运行的

我是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.

中提供的通过终端运行的流程,请查看模块。要等待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(),如何在一段时间后终止。