【问题标题】:Catch an error from command line Python从命令行 Python 捕获错误
【发布时间】:2016-12-02 18:00:12
【问题描述】:

我需要从命令行捕获错误,而不在屏幕上打印错误消息。发生这种情况时,我需要给出另一个命令来运行。

这就是我现在所做的:

hyst_cmd = "si viewhistory ..."
process = subprocess.Popen(hyst_cmd, stdout=subprocess.PIPE)
hyst = process.stdout.read().splitlines()

当我为某些项目执行此操作时,我会在屏幕上收到一条错误消息。

对不起我的英语!

【问题讨论】:

  • 您是否尝试过将此代码放入try-except 块中?这是捕获异常的好方法,您可以在 except 块中指定要运行的另一个“命令”。

标签: python command


【解决方案1】:

根据官方文档,子进程中Popen最常见的异常是OSError

要捕获错误,您可以简单地尝试以下方法:

hyst_cmd = "si viewhistory ..."

try:
    process = subprocess.Popen(hyst_cmd, stdout=subprocess.PIPE)
    hyst = process.stdout.read().splitlines()

except OSError:
    <write_log_file or other action.>

欲了解更多信息,您可以查看以下链接:
Subprocess Exception

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-13
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-10
    相关资源
    最近更新 更多