从python源文件导入函数

由于笔者最近做上了助教,然后就面对要改上百份python作业的困境。

然后就研究了一下怎么从py文件中直接导入函数的方法。

废话不多说,现在我的目标是要从一个文件夹 mydir 中导入 test.py 文件里的 myfunction 函数:

文件夹结构是这样的:

➜ Downloads tree mydir
mydir
└── test.py

test文件里的函数长这样:

def myfunction():
    print 'this is a test file'

要用到python里的 imp 包的 imp.load_source() 函数:


import imp

# import from each script
def import_function(dirname,filename,function_name):
    try:
        module = imp.load_source(dirname,filename)
        function = getattr(module,function_name)
        print('>>>>>>>> successfully parse file %s' % filename)
        return function
    except:
        print('>>>>>>>> file %s import error' % filename)

你可能感兴趣的:(从python源文件导入函数)