简体   繁体   中英

Python: passing a library function from command line

$python example.py --function cos(x)

x = [...]

def foo(f, x):
    return f(x)

Is there a smart way I can pass any function (let's say any mathematic functions defined in numpy for simplicity) from the command line so that it will produce the same result that would produce the following piece of code:

foo(lambda t: numpy.cos(t), x)

As you have specified python2.7 , you can use the import_module function from the backported importlib module.

>>> np = importlib.import_module('numpy')
>>> cos = getattr(np, 'cos')
>>> cos
<ufunc 'cos'>
>>> cos(3.14159)
-0.99999999999647926

You would need to parse the command line options (using argparse as @HenryKeiter suggests in the comments), then split the function from the module string, import the module and use getattr to access the function.

>>> def loadfunc(dotted_string):
...     params = dotted_string.split('.')
...     func = params[-1]
...     module = '.'.join(params[:-1])
...     mod =  importlib.import_module(module)
...     return getattr(mod, func)
...
>>> loadfunc('os.getcwd')
<built-in function getcwd>
>>> loadfunc('numpy.sin')
<ufunc 'sin'>
>>> f = loadfunc('numpy.cos')
>>> f(3.14159)
-0.99999999999647926

Note this doesn't load functions from the global namespace, and you might want to add some error checking.

EDIT

There is also no need for the lambda function in this line

foo(lambda t: numpy.cos(t), x)

You can just pass numpy.cos directly without evaluating it

foo(numpy.cos, x)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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