1

So, I'm trying to make a calculator in Python 3.5 and here's the outline of what I'm trying to do:

def getOut(code):
  result=exec(code, use="PyShell").stdout() #Use python shell to do command [code].
  return result #Return [result].
code=input("Problem: ") #Get problem/command.
print(f'The answer is: {getOut(code)}.') #Print result of command.

Is there any way to get the stdout of it? I wanna use (emulated) Python shell, but don't want to use the viewable Python shell.

KaiLando
  • 23
  • 7
  • Use `eval()` instead of `exec()`. See https://stackoverflow.com/questions/2220699/whats-the-difference-between-eval-exec-and-compile – Barmar Apr 20 '23 at 00:32

1 Answers1

0

you can use this simple trick (which is somewhat similar to what dataclasses do to generate the __init__ methods for dataclasses dynamically)

for example, we can generate the below function dynamically using exec, and return it

code = """
def func(a, b, c):
    return a + b + c

globals()["result"] = func
"""

# just a plain dict
container = {}

# execute code which generates the function
exec(code, container)

# get the item from the exec's globals scope
result_func = container["result"]
res = result_func(1, 2, 3)
print(res)
>>> 6
ddjerqq
  • 61
  • 1
  • 3