如何使用完整的路径导入python包或qinit_uuy.py文件?

2024-09-30 16:31:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包:pyfoo在目录/home/user/somedir中

这个包裹是普通的 '/home/user/somedir/pyfoo/\uu init\uy.py'

我希望能够使用其完整路径“/home/user/somedir/pyfoo/”导入此模块

如何对非程序包模块执行此操作,请参见: How to import a module given the full path?

但是当模块是一个包的时候,我似乎不能让它工作。在


我发现的一个非常奇怪的用例是,在用h5py写入一个文件之前,我被深深地嵌入到脚本执行中。在

我不得不卸载h5py并用openmpi重新安装一个并行版本,但是即使卸载了它,h5py(串行)仍然在内存中。我不想重新启动,因为脚本花了很长时间。我试图重新加载模块,但没用。我还试图从文件名导入它,方法是使用目录并使用\uu init_uu.py,但是我得到了相对的导入错误。我甚至尝试将新的安装位置添加到系统路径执行正常的导入,但也失败了。在

我已经在我的个人实用程序库中有一个import_from_filepath函数,我还想添加import_from_dirpath,但我在弄清楚它是如何实现的方面有点麻烦。在


下面是一个脚本来说明这个问题:

    # Define two temporary modules that are not in sys.path
    # and have the same name but different values.
    import sys, os, os.path
    def ensuredir(path):
        if not os.path.exists(path):
            os.mkdir(path)
    ensuredir('tmp')
    ensuredir('tmp/tmp1')
    ensuredir('tmp/tmp2')
    ensuredir('tmp/tmp1/testmod')
    ensuredir('tmp/tmp2/testmod')
    with open('tmp/tmp1/testmod/__init__.py', 'w') as file_:
        file_.write('foo = \"spam\"\nfrom . import sibling')
    with open('tmp/tmp1/testmod/sibling.py', 'w') as file_:
        file_.write('bar = \"ham\"')
    with open('tmp/tmp2/testmod/__init__.py', 'w') as file_:
        file_.write('foo = \"eggs\"\nfrom . import sibling')
    with open('tmp/tmp1/testmod/sibling.py', 'w') as file_:
        file_.write('bar = \"jam\"')

    # Neither module should be importable through the normal mechanism
    try:
        import testmod
        assert False, 'should fail'
    except ImportError as ex:
        pass

    # Try temporarilly adding the directory of a module to the path
    sys.path.insert(0, 'tmp/tmp1')
    testmod1 = __import__('testmod', globals(), locals(), 0)
    sys.path.remove('tmp/tmp1')
    print(testmod1.foo)
    print(testmod1.sibling.bar)

    sys.path.insert(0, 'tmp/tmp2')
    testmod2 = __import__('testmod', globals(), locals(), 0)
    sys.path.remove('tmp/tmp2')
    print(testmod2.foo)
    print(testmod2.sibling.bar)

    assert testmod1.foo == "spam"
    assert testmod1.sibling.bar == "ham"

    # Fails, returns spam
    assert testmod2.foo == "eggs"
    assert testmod2.sibling.bar == "jam"

在系统路径无法通过路径导入。它默认导入先前加载的模块。在


Tags: 模块thepathpyimportfoosysbar
1条回答
网友
1楼 · 发布于 2024-09-30 16:31:07

在Python中,通常不从绝对路径导入。这是可能的,但它会破坏模块中的导入。在

您要做的是调整PYTHONPATH。它告诉python在哪里查找要导入的内容。您可以在调用脚本之前设置环境变量PYTHONPATH,也可以在运行时查看和操作它。为此,请更改sys.path。这是一个列表,你可以append()其他路径。在

另一个选择是使用虚拟环境,它们为不同的项目和项目设置提供了特殊的python环境。阅读http://docs.python-guide.org/en/latest/dev/virtualenvs/来了解它。在

如果仍要按路径导入,请阅读How to import a module given the full path?。在

相关问题 更多 >