Python 有没有一种方法可以使用用户输入来调用函数?
我知道字符串是不可调用的,但是如果能够使用这样的代码就好了Python 有没有一种方法可以使用用户输入来调用函数?,python,Python,我知道字符串是不可调用的,但是如果能够使用这样的代码就好了 def test1(): print('7') def test2(): print('7') def test3(): print('7') def test4(): print('7') def test5(): print('7') i = input(">") #assume the input is one of the function names
def test1():
print('7')
def test2():
print('7')
def test3():
print('7')
def test4():
print('7')
def test5():
print('7')
i = input(">") #assume the input is one of the function names
i()
有两种方法: 最简单的方法是在字典中收集所有符合条件的函数:
functions = {f.__name__: f for f in [test1, test2, test3, test4, test5, test6]}
functions[input(">")]()
或者,通过使用globals()
,您只需小心,您将有效地允许用户调用全局范围内的任何函数,而不仅仅是您认为应该调用的函数:
globals()[input(">")]()
或者使用eval()
的超级偷偷摸摸的方法,或者如果您在循环中执行此操作,则只需启动一个shell即可使用来允许完全执行任意代码,这也将允许用户指定函数参数,并在运行代码的用户帐户有权限的情况下重新格式化硬盘:
import code
code.interact()
你可以使用函数字典
def test1():
print('7')
def test2():
print('7')
def test3():
print('7')
def test4():
print('7')
def test5():
print('7')
d={'test1':test1,'test2':test2,'test3':test3,'test4':test4,'test5':test5}
i = input(">") #assume the input is one of the function names
d.get(i)()
您可以使用ast模块:
from ast import literal_eval
literal_eval(input("What do you want to make me do? ")
literal_eval允许您调用字符串,如果它们包含有效的python代码。然而,正如Lie Ryan在上面警告的那样,这种方法使用户能够调用任何可能是恶意或其他破坏性代码。使用字典:
{“test1”:test1,“test2”:test2}[“test2”]()
您可以使用eval,但它仍然不安全eval(i)()