目前我正在用Python为自己编写一个小型IDE,并希望以Python代码的形式执行编辑器的文本。我将编辑器的文本作为字符串获取。我想执行代码,保存输出
&;字符串变量(o
和e
)中出现错误,然后我在IDE中呈现输出
只要我没有任何错误(my_code
),它就可以正常工作。一旦我执行了包含错误的代码(my_code_with_error
-注释如下),代码似乎没有返回并且“无声”崩溃。事实上,我甚至在Pycharm中得到了Process finished with exit code 0
——可能是因为我将sys.stdout
切换到了我自己的StringIO
实例
如何执行代码字符串,即使它有错误,然后将错误/正常输出保存在变量中作为字符串
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?)
尝试在Try/except块中包围执行代码
您可以通过捕获异常来实现这一点:
雷蒙德在我写我的答案时也给出了类似的答案。 Raymond的答案在Python2中也可以使用(请参见“问题”中的https://wiki.python.org/moin/HandlingExceptions,“一般错误处理”),并且还具有输出错误类的优势
相关问题 更多 >
编程相关推荐