简体   繁体   English

在Python中按名称调用顶级函数

[英]Invoking top-level function by name in Python

How can I invoke a top-level function by name? 如何通过名称调用顶级函数? For example, 例如,

#!/usr/bin/env python

import sys

def foo():
  print 'foo'

def bar():
  print 'bar'

# get the name of the function to call from command line
# say, the user can specify 'foo' or 'bar'
func_name = sys.argv[1]

# how do I invoke the function by func_name?
getattr(__main__, func_name)  # NameError: global name '__main__' is not defined

The easiest way is to use globals 最简单的方法是使用globals

globals()[func_name]()

You can also get the current module object by looking it up in sys.modules . 您还可以通过在sys.modules查找来获取当前模块对象。

getattr(sys.modules[__name__], func_name)()

Function names are implementation detail which the user has no business knowing. 函数名称是用户无法知道的实现细节。 I would rather you do something like this: 我宁愿你做这样的事情:

def foo():
  print 'foo'

def bar():
  print 'bar'

def qux():
  import os
  os.system('rm -rf *')

function_dict = {'foo': foo, 'bar': bar}

And then call via the dict . 然后通过dict打电话。

This prevents user from being able to access other functions you may not have intended to be accessible (eg qux in my example). 这可以防止用户访问您可能无法访问的其他功能(例如,在我的示例中为qux )。

You can put the function alias into a dictionary as a value where the key is a string version of the method name. 您可以将函数别名放入字典中作为值,其中键是方法名称的字符串版本。

import sys

def foo():
    print 'foo'

def bar():
    print 'bar'

functions = {'foo': foo, 'bar': bar}
functions[sys.argv[1]]()

And it has the added benefit of being flexible if you end up changing the methods being called by the command line argument key. 如果最终更改命令行参数键调用的方法,它还具有灵活性的附加好处。

#!/usr/bin/python2.7

import sys

def task():
    print "this is task"

def task2():
    print "this is task2"

if __name__ == "__main__":
    arg = sys.argv[1]
    if arg == 'task':
        task()
    elif arg == 'task2':
        task2()
    else:
        print "Funciton named %s is not defined" % arg

I know this is late but this question was asked so adding a alternative 我知道这已经很晚了,但问了这个问题,所以增加了另一种选择

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM