Suppose I have
code = '2+3'
I want to run this code in python interactive shell and get the output string in a variable.
So the result of the execution of code
would be stored in another variable called output
In this case, the output variable would be '5'.
So is there any way to do this?
def run_code(string):
# execute the string
return output # the string that is given by python interactive shell
!!! note:
exec returns None and eval doesn't do my job
Suppose code = "print('hi')" output should be 'hi'
Suppose code = 'hi' output should be
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'hi' is not defined
if you really must run strings as python code, you COULD spawn another python process with the subprocess.Popen
function, specify stdout, stderr, stdin
each to subprocess.PIPE
and use the .communicate()
function to retrieve the output.
python takes a -c argument to specify you're giving it python code as the next argument to execute/interpret.
IE python -c "print(5+5)"
will output 10
to stdout
IE
proc = subprocess.Popen(["python", "-c", code], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
print(stdout.decode('utf-8'))