【问题标题】:Import a python module without .py extension, [duplicate]导入没有 .py 扩展名的 python 模块,[重复]
【发布时间】:2013-05-26 20:34:03
【问题描述】:

我同意有类似的问题,但没有一个符合我的目的。

  • 我有一个没有 .py 扩展名的 python 脚本。
  • 我既不能更改文件名也不能添加符号链接。文件名很重要。

  • 我需要将上述文件导入到另一个 python 脚本中
  • 我已经尝试了以下

    >>> imp.load_source('test','.')
    <module 'test' from '.'>
    

    >>> importlib.import_module('test','.')
    <module 'test' from '.'>
    

    test 模块在哪里

    print 'hello world'
    

  • 我的要求是,如果文件为test.py,则导入语句的工作方式与导入时一样,即在导入时打印hello world
  • 有什么方法可以“运行”使用 imp 或 imortlib 导入的模块?

    我想补充一点,我说的是autotest project 中的一个control 文件,如果重要的话。

    【问题讨论】:

    • 我不这么认为,我已经试过了。我说必须执行导入的模块。imp没有发生这种情况
    • 模块在导入时执行。

    标签: python import


    【解决方案1】:

    您可以使用imp.load_source

    >>> import imp
    >>> mod = imp.load_source("test", "test")
    hello world
    >>> mod.a
    1
    

    abc:

    print "hello world"
    a = 1 
    

    【讨论】:

    • 它有效,顺便说一句,为什么需要'foo'?我看不出它有什么用处。
    • 好吧,输出与我的不匹配,我的输出中没有看到hello world
    • @RajeevS 它适用于我,在 shell 和 IDLE 中。
    • @RajeevS:你在做imp.load_source("test", "."),但是如果你阅读文档,它应该是imp.load_source(name, path)。你应该这样做imp.load_source('test', 'test')
    • 是的,这就是问题所在。:)
    猜你喜欢
    • 1970-01-01
    • 2011-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    • 1970-01-01
    • 2018-10-12
    相关资源
    最近更新 更多