[英]How to import Python module in another folder, without relative import and editing PYTHONPATH
This is my folder structure:这是我的文件夹结构:
.
├── main.py
├── formats
│ ├── __init__.py
│ └── writer.py
└── misc
├── __init__.py
└── util.py
In main.py
, I can import util.py
using:在main.py
中,我可以使用以下方法导入util.py
:
from misc.util import sth
However, I can't import util.py
in writer.py
, using the above statement, and this command:但是,我无法使用上面的语句和这个命令在writer.py
中导入util.py
:
python formats/writer.py
Now the simplest solution is to mess with the PYTHONPATH
: a simple export PYTHONPATH=.
现在最简单的解决方案是弄乱PYTHONPATH
:一个简单的export PYTHONPATH=.
will do it.会做的。 However, I don't like doing so, and don't like relative import.但是,我不喜欢这样做,也不喜欢相对导入。 What are my options now?我现在有什么选择?
The import mechanism is based on PYTHONPATH.导入机制基于 PYTHONPATH。
When you run python main.py
, then the directory containing main.py
is in PYTHONPATH, so all other packages there are importable as well.当您运行python main.py
时,包含main.py
的目录位于 PYTHONPATH 中,因此所有其他包也可以导入。
When you run python formats/writer.py
, then the formats
directory is in PATHONPATH and its parent directory is not, so you cannot import modules and packages which are not in formats
.当你运行python formats/writer.py
时, formats
目录在 PATHONPATH 并且它的父目录不在,所以你不能导入不在formats
中的模块和包。
What you can do, is run writer
module, but have the root directory in PATHONPATH and you can do that without even messing with environment variables:你可以做的是运行writer
模块,但在 PATHONPATH 中有根目录,你可以做到这一点,甚至不会弄乱环境变量:
cd /directory/in/which/main.py/is
python -m formats.writer
Unlike python formats/writer.py
, which changes PYTHONPATH and runs writer.py
, this keeps the default PYTHONPATH (current directory) and tells Python to look within that path for a module named formats.writer
and run that as the main module.与python formats/writer.py
不同,它更改 PYTHONPATH 并运行writer.py
,这将保留默认的 PYTHONPATH(当前目录)并告诉 Python 在该路径中查找名为formats.writer
的模块并将其作为主模块运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.