简体   繁体   English

如何在使用超时时从 python 的 subprocess.run 中捕获错误

[英]how to capture error from python's subprocess.run, while using timeout

I cannot figure out how to use python's subprocess.run to capture stdout, stderr, and exitcode ... and whatever else can be captured.我不知道如何使用 python 的 subprocess.run 来捕获 stdout、stderr 和 exitcode ......以及其他任何可以捕获的东西。 I also have to use the timeout option because some of the thousands of commands I'm running hang, ie., run interminably.我还必须使用超时选项,因为我正在运行的数千个命令中的一些命令会挂起,即无休止地运行。 I bet I have missed something obvious, and I apologize.我敢打赌我错过了一些明显的东西,我道歉。 I've spent days on this and cannot figure it out.我已经花了几天的时间,无法弄清楚。

Any help you could give me would be much appreciated.您能给我的任何帮助将不胜感激。

Here's my defective code:这是我有缺陷的代码:

seconds = timeout
try:
    proc = subprocess.run(cmd, capture_output=True, timeout=seconds)

except subprocess.TimeoutExpired:
    print('This process ran too long:\n' + cmd + '\n')
        
out, err = proc.communicate()
exitcode = proc.returncode

if len(out) == 0: out="''"
if len(err) == 0: err="''"
#
return exitcode, out, err

You're almost there.您快到了。 Instead of代替

out, err = proc.communicate()

use

out, err = proc.stdout, proc.stderr

Regarding your except clause, I'm not sure if you'll be able to get stdout, stderr and returncode after a timeout.关于您的 except 子句,我不确定您是否能够在超时后获得 stdout、stderr 和 returncode。 Give it a check.给它一个检查。 If not, then consider return "", "", 1 or something like that in your except clause.如果没有,那么请考虑在您的 except 子句中使用return "", "", 1或类似的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM