【发布时间】:2014-09-20 22:40:21
【问题描述】:
我正在尝试在 Python 3.4 中执行外部进程。当我的“命令”错误时,程序就会崩溃。如何优雅地处理错误并恢复?
# Call a system process
try:
pipe = subprocess.Popen(command,
stdout=subprocess.PIPE)
except (OSError,
subprocess.CalledProcessError) as error:
print("Failed to execute command")
print(command)
print("Error: " + error.output)
while True:
output = pipe.stdout.readline()
if not output:
print("Finished...")
break
output = output.decode()
output = output.strip("\r")
output = output.strip("\n")
print(output)
当我调用无效命令时。我遇到这样的崩溃:
C:\SDKs\Python34\python.exe C:\Users\user\Documents\GitHub\PyQtApps\QtDeploy\src\main.py
Traceback (most recent call last):
Executing: windeployqt.exe C:\Users\user\Documents\GitHub\SpaCentralSoftBin\GUIController.exe
File "C:\Users\user\Documents\GitHub\PyQtApps\QtDeploy\src\forms\maindialog.py", line 81, in execute_windeployqt
Failed to execute command
stdout=subprocess.PIPE)
windeployqt.exe C:\Users\user\Documents\GitHub\SpaCentralSoftBin\GUIController.exe
File "C:\SDKs\Python34\lib\subprocess.py", line 858, in __init__
restore_signals, start_new_session)
File "C:\SDKs\Python34\lib\subprocess.py", line 1111, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\user\Documents\GitHub\PyQtApps\QtDeploy\src\forms\maindialog.py", line 159, in on_buttonBox_clicked
self.execute_windeployqt()
File "C:\Users\user\Documents\GitHub\PyQtApps\QtDeploy\src\forms\maindialog.py", line 86, in execute_windeployqt
print("Error: " + error.output)
AttributeError: 'FileNotFoundError' object has no attribute 'output'
【问题讨论】:
-
不相关:您可以使用 for 循环逐行读取输出:
for line in p.stdout: sys.stdout.buffer.write(line)# + do something else with the line。为避免手动解码字节,您可以指定universal_newlines=True(它还将'\r'、'\r\n'转换为'\n'),然后您可以将其读取为:for line in p.stdout: print(line, end='')。要将 stderr(可能出现错误的地方)与 stdout 合并,请指定stderr=subprocess.STDOUT。 -
@J.F.Sebastian 谢谢!这很有用。目前,我单独阅读 stderr 以显示进程是否返回错误。你知道如何在不读取缓冲区的情况下检查是否有错误(就像在 for 循环中那样)。我需要设置一个布尔变量。
标签: python python-3.x subprocess