【问题标题】:Import Dynamically Created Python Files导入动态创建的 Python 文件
【发布时间】:2009-07-20 22:37:22
【问题描述】:

我正在通过运行 python 程序来创建 python 文件。然后我想导入这些文件并运行其中定义的函数。我正在创建的文件没有存储在我的路径变量中,我更愿意保持这种方式。

最初我是调用execFile(<script_path>) 函数,然后调用通过执行文件定义的函数。这有一个副作用是总是输入 if __name__ == "__main__" 条件,而我目前的设置是不可能发生这种情况的。

我无法更改生成的文件,因为我已经创建了 100 个并且不想全部修改它们。我只能更改调用生成文件的文件。

基本上我现在所拥有的......

#<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")

【问题讨论】:

  • 无关提示:切勿在代码中对文件名使用反斜杠。写“c:/file.py”;它适用于 Windows,并且对于解析路径的所有内容都更加一致。

标签: python import


【解决方案1】:

使用

m = __import__("File")

这和做的基本一样

import File
m = File

【讨论】:

  • 它确实是一样的,所以如果我正确阅读他的“我正在创建的文件没有存储在我的路径变量中,我更愿意保持这种方式”的话并不能解决 Halfcent 的问题.
  • 或者只是忽略无用的约束。这些文件可以放在一个子包中,不受项目根包中其他模块的影响。
【解决方案2】:

如果我正确理解您对 man 的评论,即该文件不在 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.spliy提取'c:/'和'thefile.py'部分,从'thefile.py'得到'thefile' os.path.splitext.)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-05
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-19
    • 2016-07-21
    • 2018-05-13
    相关资源
    最近更新 更多