Python从用户输入调用函数
你能从用户输入中调用函数吗?就像这样:
def testfunction(function):
function()
a = raw_input("fill in function name: "
testfunction(a)
所以如果你输入一个已经存在的函数,它就会被执行。
3 个回答
2
是的,你可以这么做,不过这通常不是个好主意,而且会有很大的安全隐患。
def testfunc(fn):
fn()
funcname = raw_input('Enter the name of a function')
if callable(globals()[funcname]):
testfunc(globals()[funcname])
3
我可能会把这种行为放在一个类里面:
class UserExec(object):
def __init__(self):
self.msg = "hello"
def get_command(self):
command = str(raw_input("Enter a command: "))
if not hasattr(self, command):
print "%s is not a valid command" % command
else:
getattr(self, command)()
def print_msg(self):
print self.msg
a = UserExec()
a.get_command()
正如其他人所说,这样做有安全风险,但你对输入的控制越多,风险就越小;把它放在一个包含仔细检查输入的类里会更安全。
4
你现在做的事情可不好哦 :P 不过,这样做是完全可以的。
a = raw_input("Fill in function name:")
if a in locals().keys() and callable(locals()['a']):
locals()['a']()
else:
print 'Function not found'
locals()
会返回一个字典,里面包含了当前所有可用的对象和它们的名字。所以当我们说 a in locals().keys()
时,其实是在问:“有没有一个叫做 a 的对象?”如果有的话,我们就可以通过 locals()['a']
来获取这个对象,然后用 callable
来检查它是不是一个函数。如果是的话,我们就可以调用这个函数。如果不是,我们就简单地打印出 "找不到这个函数"
。