【问题标题】:How to recognize an error when saving cmd result from command prompt as a string in python?将命令提示符的cmd结果保存为python中的字符串时如何识别错误?
【发布时间】:2021-05-25 15:58:49
【问题描述】:

此代码在命令提示符下运行 python 命令并将输出保存为字符串:

output = subprocess.run(
        ["python3", "-c", "print("hello")\njj" ], stdout=subprocess.PIPE, timeout=3)
    output = output.stdout.decode('utf-8')
print(output)

输出将是:

hello

在我自己的 cmd 中出现异常:

Traceback (most recent call last):
File "<string>", line 4, in <module>
NameError: name 'jj' is not defined

我试着写了一个 try and except 但它也不起作用。

我希望输出也能捕捉到错误,它看起来像这样:

hello
Traceback (most recent call last):
File "<string>", line 4, in <module>
NameError: name 'jj' is not defined

【问题讨论】:

  • 你为什么要使用subprocess从python内部运行一个新的python解释器?从 python 内部运行 python 代码有很多更好的方法...
  • 例如..?我不想打开新文件
  • 为什么不把“损坏的”打印行放在 try/except 块中?为什么将它包装在一个新的 python 解释器中?您可能需要解释您想要实现的目标,因为这看起来像是 X/Y 问题。
  • 在我的程序中我不知道实际的代码,我只能通过字符串获取它

标签: python-3.x exception command-prompt


【解决方案1】:

这可能不是最实用的,但这是我最终做的:

txt_str = 'print("hello")\njj'.split("\n")
command = "\t".join([txt + \n for txt in txt_str])
command = "try:\n" \
         "\t%s\n" \
         "except Exception as e:\n" \
         "\tprint(e)" % (command, )
output = subprocess.run(
    ["python3", "-c", command], stdout=subprocess.PIPE, timeout=3)
output = output.stdout.decode('utf-8')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    • 2021-08-01
    • 2013-12-30
    相关资源
    最近更新 更多