导入动态创建的Python文件

2 投票
2 回答
2235 浏览
提问于 2025-04-15 13:02

我正在运行一个Python程序的过程中创建Python文件。然后我想导入这些文件,并运行里面定义的函数。这些我创建的文件并不在我的路径变量中,我希望保持这种状态。

最开始我使用了execFile(<script_path>)这个函数来执行文件,然后调用执行后定义的函数。但这样做有个副作用,就是总是会进入if __name__ == "__main__"这个条件,而在我现在的设置下,我不希望发生这种情况。

我不能修改已经生成的文件,因为我已经创建了上百个,不想一个个去改。我只能修改调用这些生成文件的那个文件。

基本上我现在的情况是……

#<c:\File.py>
def func(word):
   print word

if __name__ == "__main__":
   print "must only be called from command line"
   #results in an error when called from CallingFunction.py
   input = sys.argv[1]

#<CallingFunction.py>
#results in Main Condition being called
execFile("c:\\File.py")
func("hello world")

2 个回答

3

如果我理解得没错,你提到的文件不在 sys.path 里,而且你希望保持这个状态,那么这样做还是可以的:

import imp

fileobj, pathname, description = imp.find_module('thefile', 'c:/')
moduleobj = imp.load_module('thefile', fileobj, pathname, description)
fileobj.close()

(当然,给定 'c:/thefile.py',你可以用 os.path.split 来提取出 'c:/' 和 'thefile.py' 这两个部分,然后再用 os.path.splitext 从 'thefile.py' 中得到 'thefile'。)

5

使用

m = __import__("File")

这基本上和这样做是一样的

import File
m = File

撰写回答