【问题标题】:How to get an exit code in Python?如何在 Python 中获取退出代码?
【发布时间】:2020-12-16 16:13:46
【问题描述】:

我正在研究异常和错误退出代码,但我的终端没有在 Windows 10 上的 Python 3.8 中为我提供退出代码。

我希望能够从一个简单的 "hello world" 程序中看到消息 "Process finished with exit code 0"

【问题讨论】:

  • docs.python.org/3/library/sys.html?#sys.exit - 你在哪个部分有问题?欢迎来到 SO。这不是讨论论坛或教程。请使用tour 并花时间阅读How to Ask 以及该页面上的其他链接。
  • 相关:Exit codes in PythonHow to terminate a Python scriptHow to throw error and exit with a custom message in python。使用python exit code message site:stackoverflow.com 进行更多搜索 - 它们中的任何一个都符合您的需求吗?如果是这样,请选择一个并投票以重复结束您的问题。
  • “进程以退出代码结束”是 PyCharm 打印的消息。显示退出代码不是您的 Python 程序的责任 - 毕竟,要拥有退出代码,您的程序必须已经退出。 (您不能在退出 before 之前打印,因为某些东西可能会捕获 SystemExit 或做其他事情来改变退出的发生方式。)
  • 您需要从程序外部检查退出代码。如何做到这一点取决于您运行它的方式 - 例如,在 Windows 命令提示符下,您可以使用 %errorlevel%
  • 我想 Monica 可能找​​到了我需要的东西,谢谢!

标签: python python-3.x windows exception exit


【解决方案1】:

编辑答案: 您的练习中一定有一些未处理的异常/错误,因此它不会以 exit code 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)

【讨论】:

  • 这不是我要找的,我的问题可能与不同终端如何处理 python 程序(pycharm、cmd、powershell)有关。我正在上课,练习没有“打印(“进程完成,退出代码0”)行,它只出现在最后的终端上。
  • 进程结束时exit code 0表示进程成功,否则有exit code 1 or more等问题.我建议学习 python subprocess 模块或一般 Interacting with OS using Python
  • @FredhRodrigues 行“进程以退出代码 0 完成”出现在 END 中,因为在运行练习时没有捕获到运行时异常。 (退出代码 0 表示您的练习成功运行)而退出代码 0 以外 可能表示练习中捕获的一些特定错误/异常
【解决方案2】:

享受这个完整的解释演示。

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'').

    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-03
    • 1970-01-01
    • 2021-08-16
    相关资源
    最近更新 更多