如何在python中使用带有超时间隔的子进程运行命令

时间:2019-06-07 08:02:07

标签: subprocess python-3.6

我正在尝试使用子进程模块执行python脚本。它工作良好且没有超时。这里是我用来与子进程一起运行的python脚本:

sample.py

count=0
while(True):
    print(count)
    count+=1

问题是sample.py无限执行。所以我试图设置一个超时来运行此脚本。我已经用谷歌搜索了,其中一些建议使用check_output()函数来使用timeout获得结果。所以我改变了,

out = check_output('python3 /home/gomathi/sample.py', stderr=STDOUT, timeout=5,shell=True)

但这对我不起作用,即使超时后,它仍然执行sample.py。

我应该使用什么来解决此问题?

python版本:3.6.7

out=subprocess.Popen(['python3 /home/gomathi/sample.py'],stdout=subprocess.PIPE,stderr=subprocess.STDOUT,shell=True)

然后我将子过程更改为check_output函数:

out = check_output('python3 /home/gomathi/sample.py', stderr=STDOUT, timeout=5,shell=True)

我希望脚本(sample.py)一旦超时就应该停止运行。

0 个答案:

没有答案