导入没有.py扩展名的python模块, [英] Import a python module without .py extension,

查看:162
本文介绍了导入没有.py扩展名的python模块,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I agree that there are similar questions,but none serve my purpose.

  • 我有一个python脚本,没有.py扩展名。

  • 我既不能更改文件名也不能添加符号链接。文件名很重要。

    I can neither change the file name nor add a symlink. The file name is significant.

  • 我需要将上述文件导入另一个python脚本
  • 我试过以下

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

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

    模块 test 只是

    print 'hello world'
    

  • 我的要求是如果文件是 test.py ,则import语句就像导入语句一样,即打印 hello world 导入时。
  • My requirement is that the import statement works just like it imports if the file was test.py,that is,prints hello world upon import.
  • 有没有办法运行使用imp或imortlib导入的模块?

    Is there any way to "run" the module imported by using imp or imortlib?

    我想补充一点,我在讨论控制文件: //github.com/autotestrel =nofollow>自动测试项目,如果重要的话。

    I would like to add that I am talking about a control file in the autotest project,if it matters.

    推荐答案

    您可以使用 imp.load_source

    You can use imp.load_source

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

    abc:

    print "hello world"
    a = 1 
    

    这篇关于导入没有.py扩展名的python模块,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆