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 
2
  • You're looking for eval Commented Oct 30, 2020 at 10:50
  • also consider ast.literal_eval() slightly safer than the eval Commented Oct 30, 2020 at 10:55

2 Answers 2

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'))
Sign up to request clarification or add additional context in comments.

1 Comment

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
0

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

eval(string)

1 Comment

eval("print('h')") does not return anything. I am looking for something, that will always return the output. Whatever output in in stdout

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.