2016-04-15 51 views
1

我有一个file1.py打电话从控制台一个函数作为参数

def battery(): 
    pass 

// much more methods here 

if __name__ == "__main__": 
    cmd = str((sys.argv)[1]) + "()" 
    os.system(cmd) 

现在我想用python file1.py battery调用file1.battery()从Linux控制台。

但我得到的错误:

sh: 1: Syntax error: end of file unexpected 

回答

1

可以使用eval编译字符串如代码或使用全局当地人

def func(): 
    return 'hello' 

print eval('func()') 
print globals()["func"]() 
print locals()["func"]() 

>>> hello 
>>> hello 
>>> hello 

此外,该模块可以导入自己:

import sys 

current_module = sys.modules[__name__] 
function = getattr(current_module, 'func') 
print function() 
+0

要注意,在考虑用户输入时,使用eval是非常危险的。 'eval(rm -rf /)'不好。 – Tommy

相关问题