简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM