gpt4 book ai didi

python - 在 Python 3.4 中调用子进程并在命令无效时处理错误?

转载 作者:行者123 更新时间:2023-11-28 16:36:50 25 4
gpt4 key购买 nike

我正在尝试在 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'

最佳答案

更大的问题是打印一条错误消息并没有“处理”任何有意义的“处理”意义上的错误(尽管许多人认为它确实如此)。

如果需要,记录一条错误消息,然后退出您的程序。在少数情况下您可以处理错误,例如,如果无法读取配置文件,请查看是否可以读取全局配置文件,或者是否可以将 KeyboardInterrupt 传递给正在读取命令的主循环。

在您的示例中,如果您没有在 except block 中出错,则 output = pipe.stdout... 将产生:

NameError: name 'pipe' is not defined

如果您发现了这一点,仍然没有任何有意义的事情可以恢复您的代码预期的状态。您还将移动您确实到达的回溯到没有错误的地方。

适合您情况的成语是

except SomeError:
log what you want
raise

空的 raise 会重新引发最后一个异常,该异常会向上传播,形成完整的堆栈跟踪,让您更好地了解错误所在。如果不这样做,就会丢弃有用的信息。

关于python - 在 Python 3.4 中调用子进程并在命令无效时处理错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25017336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com