繼續from my previous question我看到,要獲取我在python中通過Popen生成的進程的錯誤代碼,我必須調用wait()或communic()(它可以用來訪問POPEN輸出和錯誤的屬性):Python Popen - 等待與通信vs CalledProcessError
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()
可能死鎖(當標準輸出=管,這是這裏的情況),而communicate()
可能溢出。所以:
- 什麼是適當的東西在這裏使用?請注意,我確實使用輸出
我應該如何使用通信?難道是:
process = Popen(command, stdout=PIPE, startupinfo=startupinfo) out = process.communicate()[0] # same as before... result = process.returncode if result: # ...
不確定阻止和內存錯誤
- 任何處理問題的更好/更Python的方式?我不認爲
subprocess.CalledProcessError
or 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上,如果這有差別 - 蟒蛇2.7.8
應該有one--和最好只有一個--obvious辦法做到這一點
不相關:您的行處理代碼可能被破壞,例如,「regErrMatch(line)」只被調用一次。 – jfs
@JFSebastian:嘿謝謝 - 我認爲其意圖是'一旦'errorLine'中有東西,然後添加所有剩餘的行'(當我看到它時也困惑了我) - 可能一旦出現錯誤意味着所有其他的都會失敗 –
要downvoter - ? –