【发布时间】:2015-09-08 00:55:15
【问题描述】:
继续from my previous question 我看到要获取我在 python 中通过 Popen 生成的进程的错误代码,我必须调用 wait() 或communicate() (可用于访问 Popen stdout 和 stderr 属性) :
app7z = '/path/to/7z.exe'
command = [app7z, 'a', dstFile.temp, "-y", "-r", os.path.join(src.Dir, '*')]
process = Popen(command, stdout=PIPE, startupinfo=startupinfo)
out = process.stdout
regCompressMatch = re.compile('Compressing\s+(.+)').match
regErrMatch = re.compile('Error: (.*)').match
errorLine = []
for line in out:
if len(errorLine) or regErrMatch(line):
errorLine.append(line)
if regCompressMatch(line):
# update a progress bar
result = process.wait() # HERE
if result: # in the hopes that 7z returns 0 for correct execution
dstFile.temp.remove()
raise StateError(_("%s: Compression failed:\n%s") % (dstFile.s,
"\n".join(errorLine)))
但是the docs 警告wait() 可能会死锁(当 stdout=PIPE 时,就是这种情况),而communicate() 可能会溢出。所以:
- 在这里使用什么合适?请注意,我确实使用了输出
-
我应该如何使用通信?会不会:
process = Popen(command, stdout=PIPE, startupinfo=startupinfo) out = process.communicate()[0] # same as before... result = process.returncode if result: # ...不确定阻塞和内存错误
- 有更好/更 Pythonic 的方式来处理这个问题吗?我认为
subprocess.CalledProcessErroror thesubprocess.check_call/check_output不适用于我的情况 - 或者他们是否适用?
免责声明:我没有编写代码,我是当前的维护者,因此问题 3。
相关:
- Python popen command. Wait until the command is finished
- Check a command's return code when subprocess raises a CalledProcessError exception
- wait process until all subprocess finish?
如果这有所不同,我在 Windows 上 - python 2.7.8
应该有一种——最好只有一种——明显的方法
【问题讨论】:
-
不相关:您的行处理代码可能已损坏,例如,
regErrMatch(line)仅被调用一次。 -
@JFSebastian:嘿,谢谢-我认为目的是“一旦
errorLine中有某些内容,然后添加所有剩余的行”(当我看到它时我也感到困惑)-可能一旦有一个错误意味着一切都会失败
标签: python python-2.7 error-handling popen