简体   繁体   English

如何在python中导入您不知道其名称的函数?

[英]How to import a function that you do not know the names of in python?

So, I am trying to import a function, from a specific file, and run it, in a function on a different file. 因此,我正在尝试从特定文件导入函数,然后在其他文件上的函数中运行它。 Here is my code: 这是我的代码:

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 uses the re module and pattern matching to get all the names that appear after 'def' in a python document, and only returns the names of the functions. get_func_names使用re模块和模式匹配来获取出现在python文档中'def'之后的所有名称,并且仅返回函数的名称。 test_a_function imports the python document, opens it, applies get_func_names, and tries to evaluate the first string of a function name using the eval function, but i get an error saying the 'str' object is not callable. test_a_function导入python文档,将其打开,应用get_func_names,并尝试使用eval函数评估函数名称的第一个字符串,但是我收到一条错误消息,说“ str”对象不可调用。

Is there a way to fix my method or another way to do this? 有没有办法解决我的方法或另一种方法来做到这一点?

EDIT: 编辑:

Ok thank you for the answer, but in the end for some reason, it would only work with the importlib module 好的,谢谢您的回答,但是最后由于某种原因,它只能与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

Consider: 考虑:

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

If you don't want side effects from evaluation occurring at the module level you could use the AST module to only evaluate function definitions, but this would be considerably more work (and modules written not expecting this behavior would not necessarily function correctly). 如果您不希望在模块级别上发生评估带来的副作用,则可以使用AST模块仅评估函数定义,但这会花费更多的工作(编写的模块并不期望此行为不一定能正常运行)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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