简体   繁体   English

从同级目录导入(python 3)

[英]Importing from sibling directories (python 3)

I can't figure out how to import modules from sibling directories in Python 3 using absolute imports. 我无法弄清楚如何使用绝对导入从Python 3的同级目录中导入模块。

  1. modify the sys.path . 修改sys.path
  2. turn the directory into a pip installable package via __init__.py and setup.py . 通过__init__.pysetup.py将目录转换为pip可安装的软件包。

For option 1. I figured out how to import modules from sibling directories by modifying the sys.path , but this method seems a little hackey to me. 对于选项1,我想出了如何通过修改sys.path从同级目录中导入模块,但是这种方法对我来说似乎有点怪。 Also, I've read that it is not preferred. 另外,我读到它不是首选。 Why? 为什么? Is there something inherently wrong or dangerous about modifying the sys.path ? 修改sys.path有天生的错误或危险吗?

For option 2. What exactly do I need to do make my package pip installable? 对于选项2。我到底需要做什么才能使软件包pip可安装? I've alreay created my __init__.py file, but it seems that I need to create and configure a setup.py script to prepare my package for distribution? 我已经创建了__init__.py文件,但似乎需要创建和配置setup.py脚本来准备要分发的程序包? I'm still in the development mode, so is this really the best/pythonic method? 我仍处于开发模式,这真的是最好的/ pythonic方法吗? If it is, then do I just type python setup.py install into my terminal after creating the setup.py ? 如果是这样,那么在创建setup.py之后,我是否只需在终端中键入python setup.py install

Edit: I'm now trying to figure this out using absolute imports as python 3 does support relative imports. 编辑:我现在正试图使用​​绝对导入来弄清楚这一点,因为python 3确实支持相对导入。

From what I've read, Python 3 does not support relative imports 据我了解,Python 3不支持相对导入

It does. 是的

To import myproject/foo/__init__.py from myproject/bar/baz.py , you can use this: 要从myproject/bar/baz.py导入myproject/foo/__init__.py myproject/bar/baz.py ,可以使用以下命令:

from .. import foo

Or if you want to import an object/module in foo : 或者,如果要在foo导入对象/模块,请执行以下操作:

from ..foo import object

This requires myproject to be a package, so myproject/__init__.py has to exist. 这要求myproject是一个包,因此myproject/__init__.py必须存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM