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. 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.
It works fine as long as I don't have any errors (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. In fact I even get Process finished with exit code 0
in Pycharm - probably because I switched sys.stdout
for my own StringIO
instance.
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. (How do I execute a string containing Python code in Python?)