我想将函数定义传递给Python命令行脚本。最好的方式是什么?我正在使用Python 2。假设我有这样一个脚本:
#myscript.py
x = load_some_data()
my_function = load_function_definition_from_command_line()
print my_function(x)
我希望这样调用它:python myscript.py 'def fun(x): return len(x)'
如何执行load_function_definition_from_command_line
部分?
我想到了一种解决方法:
- 从命令行获取字符串函数定义
- 在某个临时目录中将其写入扩展名为.py的文件中
- 使用此问题的解决方案加载文件中的定义:How to import a module given the full path?
- 执行
- 清理
但我确信一定有更好的方法。