从 Python 中的相对路径导入 [英] Importing from a relative path in Python

查看:38
本文介绍了从 Python 中的相对路径导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于存放客户端代码的文件夹、一个用于存放服务器代码的文件夹以及一个用于存放它们之间共享的代码的文件夹

项目/客户/客户端.py服务器/服务器.py常见的/__init__.py通用文件

如何从 Server.py 和 Client.py 导入 Common.py?

解决方案

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.

这篇关于从 Python 中的相对路径导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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