我正在研究异常和错误的退出代码,但我的终端没有在Windows 10的Python 3.8中给我退出代码。
例如,我希望能够从简单的“ hello world” 程序中获取消息“退出代码为0的过程已完成” 。
答案 0 :(得分:0)
已编辑答案: 练习中必须有一些未处理的异常/错误,以使它不会以退出代码0 退出(表示成功执行了练习)。在程序的开头添加Try,并在示例程序的末尾捕获异常。
print()函数始终返回None,所以不要尝试从print()获取返回状态
import sys
try:
print('hello world') #print('string') - Always returns None
print("Process finished with exit code 0")
sys.exit(0)
except Exception as ex:
print("Error:"+ex)
sys.exit(1)
答案 1 :(得分:0)
享受这个完整的说明演示。
import subprocess
result = subprocess.run("C:/Windows/System32/WindowsPowerShell/v1.0/powershell.exe Write-Output 'Hello world!' ", shell=True, capture_output=True) # command to run in powershell using python subprocess module
res = result.returncode # return system-exit code of the command
out = result.stdout # return output of the powershell command
print(f"The output of the command is {out}, The exit code is {res} and the process generated by command is {result}.")
输出
The output of the command is b'Hello world!\r\n', The exit code is 0 and the process generated by command is CompletedProcess(args="C:/Windows/System32/WindowsPowerShell/v1.0/powershell.exe Write-Output 'Hello world!' ", returncode=0, stdout=b'Hello world!\r\n', stderr=b'').