如果允许用户指定函数调用和函数本身的语法,导入函数的最佳方法是什么?我用execfile
目前的实现,但是有更好的方法吗?
这是一个奇怪的应用程序,但我想方便地访问我通过可从命令行调用的 python 脚本编写的库。用户在 csv 文件中定义简单的语法,并且可以选择定义访问我的库 ( mylibrary
) 中的函数的 python 函数。
例如,这里是 csv 文件内容(“userstrings.csv”):
x,"1"
y,"2"
z,"func({x},{y})"
然后,用户可以定义func
在“用户定义.py”中:
def func(x,y):
return mylibrary.add(x,y)
主程序看起来像这样:
import csv
from collections import OrderedDict
import operator as mylibrary # this would be import mylibrary
execfile('userdefined.py')
class foo:
def __init__(self,filename):
with open(filename) as f:
strings = [string for string in csv.reader(f)]
self.strings = strings
def execute(self):
output = OrderedDict()
for label, string in self.strings:
output[label] = eval(string.format(**output))
return output
bar = foo('userstrings.csv')
print bar.execute()
这将输出
OrderedDict([('x', 1), ('y', 2), ('z', 3)])
为了制作一个可重现的示例,我刚刚定义了 mylibrary
成为operator
上面的库,但通常是 import mylibrary
.
有没有比调用 execfile
更好的方法?在这样的应用程序中创建用户定义的函数?
最佳答案
只需导入即可。
try:
import userdefined
except ImportError:
pass
用户只需将文件放置在 Python 的搜索路径中,您可以从脚本中对其进行扩充。
关于python - 包含任意用户定义的函数的最佳方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34926651/