上下文:
我正在使用python 2.7.5。
我需要从 python 脚本运行子进程,等待其终止并获取输出。
子进程运行大约 1000 次。
为了运行我的子流程,我定义了一个函数:
def run(cmd):
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = p.communicate()
return (p.returncode, stdout, stderr)
要执行的子进程是bash脚本并作为 run()
函数的 cmd
参数传递。
命令及其参数通过列表给出(正如 Popen()
所期望的那样)。
问题:
过去,它总是可以正常工作,没有任何错误。
但最近,Python 脚本在成功执行大量调用后总是卡在子进程调用上。有问题的子进程根本没有执行(bash 脚本甚至没有启动)并且 python 脚本 block 。
使用 Ctrl+C 停止执行后,我得到了卡住的地方:
[...]
File "import_debug.py", line 20, in run
(stdout, stderr) = p.communicate()
File "/usr/lib64/python2.7/subprocess.py", line 800, in communicate
return self._communicate(input)
File "/usr/lib64/python2.7/subprocess.py", line 1401, in _communicate
stdout, stderr = self._communicate_with_poll(input)
File "/usr/lib64/python2.7/subprocess.py", line 1455, in _communicate_with_poll
ready = poller.poll()
KeyboardInterrupt
我不明白为什么会出现这个问题,也不明白如何解决。
我找到了this SO thread这似乎解决了相同的问题或等效的问题(因为键盘中断后的输出是相同的),但没有答案。
问题:这里发生了什么?我缺少什么?如何解决这个问题?
<小时/>编辑:
调用的形式如下:
(code, out, err) = run(["/path/to/bash_script.sh", "arg1", "arg2", "arg3"])
print out
if code:
print "Failed: " + str(err)
bash 脚本正在对数据进行一些基本处理(解压缩存档并对提取的数据执行某些操作)。
发生错误时,不会执行任何 bash 脚本指令。
出于公司隐私考虑,我无法提供确切的命令、参数和内容。
最佳答案
您所指的原始线程的作者说:“如果我设置 stderr=None
而不是 stderr=subprocess.PIPE
我永远不会看到这个问题。 ” -- 我建议您完全这样做并让您的脚本正常运行。
阅读评论部分后添加:
有一些有用的选项,您可能想要或不使用:
-f freshen existing files, create none
-n never overwrite existing files
-o overwrite files WITHOUT prompting
关于Python 子进程卡在communicate() 调用上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59565486/