python - 包含任意用户定义的函数的最佳方式?

标签 python

如果允许用户指定函数调用和函数本身的语法,导入函数的最佳方法是什么?我用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/

相关文章:

c# - 指定的可执行文件不是此操作系统平台的有效应用程序。 Python绘图仪

python - 机器人框架和 Python 日志记录 : Logging from multiple threads and logging channel names

python - 如何使用 Pandas 选择两组中的前 N ​​组并将第二组的其余部分聚合到 "Others"中?

python,泛型函数

python - Pandas 移动行值以匹配列名

python - 如何打印前面有一定数量空格的整数?

python - 巧妙地将位置参数作为 args 和可选参数作为 kwargs 从 argparse 传递给函数

python - 向 locals() 显式添加东西有多糟糕?

python - pandas - 添加一个基于现有值的列(bins,qcut)

python - 使用 Python 和 NumPy 的非常大的矩阵