命令执行的python超时(如果未在5秒内完成)

2024-06-26 04:08:24 发布

您现在位置:Python中文网/ 问答频道 /正文

如果命令无法在5秒内完成,那么添加超时的最佳方法是什么

from subprocess import check_output
try:
    check_output("dh")
except Notexecuted:
    print"command not successful executed"

版本=python2.7


Tags: 方法fromimport命令outputchecknotcommand
1条回答
网友
1楼 · 发布于 2024-06-26 04:08:24

在Python2.7中,我们没有直接实现带有子进程的超时函数。相反,我建议使用subprocess32

from subprocess32 import Popen, PIPE

cmd = "<your command>"
response = Popen(cmd, stdout=PIPE, stderr=PIPE)
stdout, stderr = response.communicate(timeout=5)

(在python3.x中,我们有一个timeout参数,默认值为subprocess

注:参考documentation

POSIX users (Linux, BSD, etc.) are strongly encouraged to install and use the much more recent subprocess32 module instead of the version included with python 2.7. It is a drop in replacement with better behavior in many situations.

希望这对你有帮助

相关问题 更多 >