如何解决如何在Python中获得退出代码?
我正在研究异常和错误的退出代码,但我的终端没有在Windows 10的Python 3.8中给我退出代码。
例如,我希望能够从简单的“ hello world” 程序中获取消息“退出代码为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)
,
享受这个完整的说明演示。
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'').
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。