2014-10-08 24 views
-3

执行DEF例如,我有:我如何在Python从输入

def function(): 
    return 

,我想通过执行它:

d = input('Enter the def name: ') 

通过输入DEF名称(“功能”在这种情况下)。

我该怎么做?编辑==========================

找到路!

def func(): 
    print('IT WORKS!') 

r = raw_input('Function: ') 
result = eval(r+'()') 
+0

你应该使用'raw_input'而不是'input',并且你应该把函数放在字典'{'function':function}'中。 – jonrsharpe 2014-10-08 15:53:14

+0

或者,您可以使用'exec()'执行它们的输入。 – Scironic 2014-10-08 15:55:36

+3

@Scironic很少(如果有的话)一个可接受的方法 – jonrsharpe 2014-10-08 15:56:40

回答

0

以下是@ jonrsharpe的评论,您可以通过模块的名称空间获取函数。如果你是在功能模块中已经,您可以

f_name = raw_input('Enter the def name: ') 
globals()[f_name]() 

在这种情况下,如果名称不正确,KeyError异常升高。

如果该功能是在不同的模块,你可以

import functions 
f_name = raw_input('Enter the def name: ') 
getattr(functions, f_name)() 

在这种情况下,AttributeError的是,如果名称不正确引发。

+0

@ GP89 ​​ - 你说得对!定影。 – tdelaney 2014-10-08 16:01:40

+0

请勿使用'globals'。它暴露的比你期望的要多,可能造成安全漏洞。 – Andy 2014-10-08 16:01:40

+0

@安迪,这取决于情况。如果你愿意,模块字典总是随时随地玩。例如,单元测试框架使用它来查找测试用例。当我不在乎用户是否使用额外的绳索来吊起自己时,我有时会使用它。如果输入来自外部世界,您担心DOS攻击或特权提升漏洞,那么可以避免使用像这样的模块字典。 – tdelaney 2014-10-08 16:05:11

0
def function(): 
    print "In function" 
    return 

available_functions = {'function':function} 
d = raw_input('Enter the def name: ') 
available_functions[d]() 

输出:

Enter the def name: function 
In function 

定义在字典中的可用功能。您可以使用它来确定是否存在这样的功能。然后,你只需要调用你的字典中映射的那个。

available_functions = {'function':function},将输入function映射到函数名称function。它是通过这条线叫:如果用户通过一个不存在的功能available_functions[d]()

,你会得到一个关键的错误:

Enter the def name: nonasdf 
Traceback (most recent call last): 
    File "in_test.py", line 11, in <module> 
    available_functions[d]() 
KeyError: 'nonasdf' 

你可以用一个try/exceptavailable_functions[d]()各地捕捉到这一点,并输出更友好的消息:

try: 
    available_functions[d]() 
except KeyError: 
    print "Function doesn't exist" 
0

下面是一些不安全的,一个安全的方式来实现自己的目标:

def function(): 
    print "In 'function()'" 
    return 7 

# Unsafe way 
d = input('Type "function()": ') 
print "The result is",d 

# Only slightly safer 
d = input('Type "function": ') 
d = d() 
print 'The result is', d 

# Safer still, but still dangerous 
d = raw_input('Type "function": ') 
d = vars()[d]() 
print 'The result is', d 

# Probably the safest way: 
commands = { 
    'function': function 
} 
def default_command(): 
    print "Oops" 
    return 0 
d = raw_input('Type "function": ') 
d = commands.get(d, default_command) 
d = d() 
print 'The result is', d