如何在 python 中导入一个你不知道名字的函数?
How to import a function that you do not know the names of in python?
所以,我试图从一个特定文件导入一个函数,然后 运行 它在另一个文件的函数中。这是我的代码:
import re
def get_func_names(string):
temp = re.compile(r"def [a-z]+")
result = temp.findall(string)
return [elem[4:] for elem in result]
def test_a_function(val):
import swift
g = open('swift.py', 'r')
g = g.read()
functions = get_func_names(g)
k = functions[0]
k = eval(k(val))
return k
get_func_names 使用 re 模块和模式匹配获取 python 文档中出现在 'def' 之后的所有名称,并且仅 returns职能。 test_a_function 导入 python 文档,打开它,应用 get_func_names,并尝试使用 eval 函数评估函数名称的第一个字符串,但我收到一条错误消息 'str' 对象不可调用。
有没有办法修复我的方法或其他方法?
编辑:
好的,谢谢您的回答,但最终由于某些原因,它只能与 importlib 模块一起使用
import importlib
import types
def getfuncs(modulename):
retval = {}
opened = importlib.import_module(modulename)
for name in opened.__dict__.keys():
if isinstance(opened.__dict__[name], types.FunctionType):
retval[name] = opened.__dict__[name]
return retval
考虑:
import types
def getfuncs(modulename):
retval = {}
module = __import__(modulename, globals(), locals(), [], -1)
for (name, item) in module.__dict__.iteritems():
if isinstance(item, types.FunctionType):
retval[name] = item
return retval
getfuncs('swift') # returns a dictionary of functions in the swift module
如果您不希望在模块级别发生求值的副作用,您可以使用 AST 模块仅求值函数定义,但这会带来更多的工作(并且编写的模块不一定会期望这种行为正常运行)。
所以,我试图从一个特定文件导入一个函数,然后 运行 它在另一个文件的函数中。这是我的代码:
import re
def get_func_names(string):
temp = re.compile(r"def [a-z]+")
result = temp.findall(string)
return [elem[4:] for elem in result]
def test_a_function(val):
import swift
g = open('swift.py', 'r')
g = g.read()
functions = get_func_names(g)
k = functions[0]
k = eval(k(val))
return k
get_func_names 使用 re 模块和模式匹配获取 python 文档中出现在 'def' 之后的所有名称,并且仅 returns职能。 test_a_function 导入 python 文档,打开它,应用 get_func_names,并尝试使用 eval 函数评估函数名称的第一个字符串,但我收到一条错误消息 'str' 对象不可调用。
有没有办法修复我的方法或其他方法?
编辑:
好的,谢谢您的回答,但最终由于某些原因,它只能与 importlib 模块一起使用
import importlib
import types
def getfuncs(modulename):
retval = {}
opened = importlib.import_module(modulename)
for name in opened.__dict__.keys():
if isinstance(opened.__dict__[name], types.FunctionType):
retval[name] = opened.__dict__[name]
return retval
考虑:
import types
def getfuncs(modulename):
retval = {}
module = __import__(modulename, globals(), locals(), [], -1)
for (name, item) in module.__dict__.iteritems():
if isinstance(item, types.FunctionType):
retval[name] = item
return retval
getfuncs('swift') # returns a dictionary of functions in the swift module
如果您不希望在模块级别发生求值的副作用,您可以使用 AST 模块仅求值函数定义,但这会带来更多的工作(并且编写的模块不一定会期望这种行为正常运行)。