【问题标题】:Call a function from the console as an argument从控制台调用函数作为参数
【发布时间】:2016-04-15 12:56:50
【问题描述】:

我有一个file1.py

def battery():
    pass

// much more methods here

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

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

但我得到了错误:

sh: 1: Syntax error: end of file unexpected

【问题讨论】:

    标签: python linux function console arguments


    【解决方案1】:

    您可以使用eval 来编译类似代码的字符串或使用globalslocals

    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()
    

    【讨论】:

    • 请注意,在考虑用户输入时,使用 eval 是极其危险的。 eval(rm -rf /)不好。
    猜你喜欢
    • 2012-02-21
    • 1970-01-01
    • 2014-05-12
    • 2012-03-10
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    相关资源
    最近更新 更多