Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 在python中将命令提示符下的cmd结果保存为字符串时,如何识别错误?_Python 3.x_Exception_Command Prompt - Fatal编程技术网

Python 3.x 在python中将命令提示符下的cmd结果保存为字符串时,如何识别错误?

Python 3.x 在python中将命令提示符下的cmd结果保存为字符串时,如何识别错误?,python-3.x,exception,command-prompt,Python 3.x,Exception,Command Prompt,此代码在命令提示符下运行python命令,并将输出保存为字符串: output = subprocess.run( ["python3", "-c", "print("hello")\njj" ], stdout=subprocess.PIPE, timeout=3) output = output.stdout.decode('utf-8') print(output) 输出将是: hel

此代码在命令提示符下运行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
回溯(最近一次呼叫最后一次):
文件“”,第4行,在
NameError:未定义名称“jj”
我试着写了一篇尝试和例外,但它也不起作用

我希望输出也能捕捉到错误,如下所示:

hello
Traceback (most recent call last):
File "<string>", line 4, in <module>
NameError: name 'jj' is not defined
你好 回溯(最近一次呼叫最后一次): 文件“”,第4行,在 NameError:未定义名称“jj”
这可能不是最实用的方法,但这就是我最终要做的:

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

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