首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >以python代码的形式执行字符串并存储输出+错误

以python代码的形式执行字符串并存储输出+错误
EN

Stack Overflow用户
提问于 2020-10-11 18:15:35
回答 2查看 636关注 0票数 1

目前,我正在用Python为自己编写一个小型IDE,并希望以Python代码的形式执行编辑器的文本。我把编辑器的文本作为字符串得到。我想要执行代码,将输出和错误保存在字符串变量(oe)中,然后在我的IDE中呈现输出。

只要我没有任何错误(my_code),它就能正常工作。一旦我执行了包含错误的代码(下面是my_code_with_error注释),就好像代码没有返回,并且“静悄悄地”崩溃。事实上,我甚至在Pycharm中获得了Process finished with exit code 0 --可能是因为我为自己的StringIO实例切换了sys.stdout

如何执行代码字符串,即使它有错误,然后将错误/正常输出保存在一个变量中作为字符串?

代码语言:javascript
运行
复制
import sys
from io import StringIO

# create file-like string to capture output
codeOut = StringIO()
codeErr = StringIO()
print("Start")

my_code = """
print("Hello World!")
"""

my_code_with_error = """
print("Hello world!")
print(avfsd)  # error -> printing a variable that does not exist.
"""

print("Executing code...")
# capture output and errors
sys.stdout = codeOut
sys.stderr = codeErr

exec(my_code )  # this works fine
# exec(my_code_with_error)  # as soon as there is an error, it crashes silently.

# restore stdout and stderr
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
print("Finished code execution.")

e = codeErr.getvalue()
o = codeOut.getvalue()
print("Error: " + e)
print("Output: " + o)

codeOut.close()
codeErr.close()

PS:从2009年起,有一个很老的问题,我得到了一些代码,但是找不到更多关于这个主题的问题。(How do I execute a string containing Python code in Python?)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-10-11 18:31:08

尝试在try/except块中包围执行代码。

代码语言:javascript
运行
复制
try:
    exec(my_code)
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise
票数 2
EN

Stack Overflow用户

发布于 2020-10-11 18:36:43

您可以通过捕获异常来做到这一点:

代码语言:javascript
运行
复制
try:
    exec(my_code_with_error)
except Exception as e:
    print(e)

雷蒙德发布了一个类似的答案,而我正在写我的答案。雷蒙德的答案也适用于Python2(参见https://wiki.python.org/moin/HandlingExceptions,“问题”中的“通用错误处理”),并具有输出错误类的优点。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64307489

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档