user6460047
user6460047

Reputation:

How do I do something like exec() with importing my variables?

I'm trying to do something like this for a project:

def printhi():
    print("Hi")
myinput = input() # for example printhi()
exec(myinput)

Now I get an error, because exec() just starts a new session and ignores my functions and variables. How can I change that?

Upvotes: 1

Views: 58

Answers (1)

André Laszlo
André Laszlo

Reputation: 15537

The exec builtin takes two additional arguments that can be used to pass in the local and global scope:

x = 10
exec("print(x)", globals(), locals()) # Prints "10"

Update: Given your example, I think a "better" solution (or at least something more realistic) is to not use exec. To call a function given by the user, try something like:

mypinput = input()
choices = {'printhi': printhi}
if myinput in choices:
    function = choices[myinput]
    function()
else:
    print("Unknown function", myinput)

Upvotes: 2

Related Questions