且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从 Python 中的相对路径导入

更新时间:2023-02-10 07:51:39

EDIT Nov 2014(3 年后):

Python 2.6 和 3.x 支持适当的相对导入,您可以在其中避免做任何麻烦的事情.使用这种方法,您知道您获得的是相对 导入,而不是绝对 导入.'..' 的意思是,转到我上面的目录:

from ..Common import Common

需要注意的是,这仅在您从包的外部将python作为模块运行时才有效.例如:

python -m Proj

原始的hacky方式

这种方法在某些情况下仍然常用,在这种情况下,您实际上从未安装"过您的软件包.例如,它在 Django 用户中很受欢迎.

您可以将 Common/添加到您的 sys.path(python 查看以导入内容的路径列表):

import sys, ossys.path.append(os.path.join(os.path.dirname(__file__), '..', 'Common'))进口通用

os.path.dirname(__file__) 只是为您提供当前 python 文件所在的目录,然后我们导航到Common/"目录并导入Common"模块.

I have a folder for my client code, a folder for my server code, and a folder for code that is shared between them

Proj/
    Client/
        Client.py
    Server/
        Server.py
    Common/
        __init__.py
        Common.py

How do I import Common.py from Server.py and Client.py?

EDIT Nov 2014 (3 years later):

Python 2.6 and 3.x supports proper relative imports, where you can avoid doing anything hacky. With this method, you know you are getting a relative import rather than an absolute import. The '..' means, go to the directory above me:

from ..Common import Common

As a caveat, this will only work if you run your python as a module, from outside of the package. For example:

python -m Proj

Original hacky way

This method is still commonly used in some situations, where you aren't actually ever 'installing' your package. For example, it's popular with Django users.

You can add Common/ to your sys.path (the list of paths python looks at to import things):

import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'Common'))
import Common

os.path.dirname(__file__) just gives you the directory that your current python file is in, and then we navigate to 'Common/' the directory and import 'Common' the module.