[英]Executing a string as python code and storing output + errors
I'm writing a small IDE for myself in Python at the moment and want to execute the text of my editor as Python code.我目前正在用 Python 为自己编写一个小型 IDE,并希望将我的编辑器的文本作为 Python 代码执行。 I get the text of my editor as a string.
我将编辑器的文本作为字符串获取。 I want to execute the code, save the ouput & errors in string-variables (
o
and e
) and then I render the output in my IDE.我想执行代码,将输出和错误保存在字符串变量(
o
和e
)中,然后在我的 IDE 中呈现输出。
It works fine as long as I don't have any errors ( my_code
).只要我没有任何错误(
my_code
),它就可以正常工作。 Once I execute code containing an error ( my_code_with_error
- commented below), it seems as if the code is not returning and "silently" crashing.一旦我执行包含错误的代码(
my_code_with_error
- 在下面评论),似乎代码没有返回并且“无声地”崩溃。 In fact I even get Process finished with exit code 0
in Pycharm - probably because I switched sys.stdout
for my own StringIO
instance.事实上,我什至在 Pycharm 中
Process finished with exit code 0
- 可能是因为我为我自己的StringIO
实例切换了sys.stdout
。
How can I execute the code-string, even if it has errors and then save the error / normal output in a variable as a String?如何执行代码字符串,即使它有错误,然后将错误/正常输出作为字符串保存在变量中?
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: There was a really old question from 2009 where I got some of my code, but can't find any more recent questions concerning this topic. PS:2009 年有一个非常老的问题,我在那里得到了一些代码,但找不到关于这个主题的任何最近的问题。 ( How do I execute a string containing Python code in Python? )
( 如何在 Python 中执行包含 Python 代码的字符串? )
Try surrounding the execution code in a try/except block.尝试在 try/except 块中包围执行代码。
try:
exec(my_code)
except:
print("Unexpected error:", sys.exc_info()[0])
raise
You can do that by catching the exceptions :您可以通过捕获异常来做到这一点:
try:
exec(my_code_with_error)
except Exception as e:
print(e)
Raymond posted a similar answer as I was writting mine.雷蒙德在我写我的时候发布了一个类似的答案。 Raymond's answer works in Python 2 also (see https://wiki.python.org/moin/HandlingExceptions , "General Error Handling" in "Questions") and has the advantage of outputing the error class too.
Raymond 的答案也适用于 Python 2(请参阅https://wiki.python.org/moin/HandlingExceptions ,“问题”中的“一般错误处理”)并且也具有输出错误类的优势。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.