0

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 
aahnik
  • 1,661
  • 1
  • 11
  • 29

2 Answers2

1

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'))
JackofSpades
  • 113
  • 1
  • 8
  • this is the perfect solution I was looking for. I would actually put it into a function and return the decoded stdout and stderr. thanks a lot – aahnik Oct 30 '20 at 11:58
0

The function you are looking for is the built in python function

eval(string)
  • eval("print('h')") does not return anything. I am looking for something, that will always return the output. Whatever output in in stdout – aahnik Oct 30 '20 at 11:16