2012-12-04 46 views
0

我想从linux命令提示符运行python函数。因此,我定义了一个函数和从linux输入到要执行的函数的映射字典。因此,如。字典中的映射函数

def help(): 
    print(...) 

def dostuff(): 
    do sth 

functions ={ 
    'help': help()' 
    ''dostuff' : dostuff() 
    } 

def parsecommand(): 
    return functions[sys.argv] 

if __name__='__main__': 
    parsecommand()  

当我现在运行在Linux的功能,[蟒蛇filename.py]帮助现在的问题是,通过在字典中的所有功能,是蟒蛇运行和构建字典时执行它们。我怎样才能避免这种情况? 或者什么是更好的方法来构造这个?

回答

3

改变你的字典,像这样:

functions = { 
    'help': help, 
    'dostuff' : dostuff 
    } 

这将允许您调用函数以下列方式:

functions[sys.argv[1]]() 
+0

辉煌。它做到了。谢谢 – chrise

0
functions = { 
    'help': help, 
    'dostuff': dostuff 
} 

def parsecommand(): 
    return functions[sys.argv]() 
2

取出()旁边的函数名字典。

functions ={ 
    'help': help 
    'dostuff' : dostuff 
} 

你会比能够运行的功能,像这样:

return functions[sys.argv[1]]()