[英]Absolute and relative imports not working for custom package
I have a package (or what I think should be a package) with a directory structure:我有一个带有目录结构的 package (或者我认为应该是一个包):
Switch/
tests/
testing.py
Sw.py
#otherfiles
I am trying to import Sw.py from testing.py.我正在尝试从 testing.py 导入 Sw.py。 I have tried several things, including
from.. import Sw
, import..Sw
, from Switch import Sw
and several other variations.我尝试了几件事,包括
from.. import Sw
、 import..Sw
、 from Switch import Sw
和其他几个变体。 I have tried these with and without and __init__.py
file in the Switch directory and in the tests directory.我已经在 Switch 目录和测试目录中尝试了这些有和没有
__init__.py
文件。 The primary error I'm getting is:我得到的主要错误是:
Traceback (most recent call last):
File "tests/testing.py", line 10, in <module>
from .. import Sw
ImportError: attempted relative import with no known parent package
Though I also get syntax errors when I try import..Sw
and ModuleNotFoundError: No module named 'Switch'
when I try from Switch import Sw
.虽然当我尝试
import..Sw
和ModuleNotFoundError: No module named 'Switch'
当我尝试from Switch import Sw
时我也会遇到语法错误。
I have done my best to ensure none of the directories in the package are in the path or pythonpath, though I am on WSL running Python installed on Windows, so the paths are somewhat complex.尽管我在 WSL 上运行 Python 安装在 Windows 上,但我已尽力确保 package 中的所有目录都不在路径或 pythonpath 中,所以路径有些复杂。
When I go to the directory above Switch and run python -c "import Switch.Sw"
it works correctly, but inside the Switch directory it responds with ModuleNotFoundError: No module named 'Switch'
当我 go 到 Switch 上面的目录并运行
python -c "import Switch.Sw"
它工作正常,但在 Switch 目录中它响应ModuleNotFoundError: No module named 'Switch'
Use this code to go up a directory and then you should be able to import from your package使用此代码到 go 一个目录,然后你应该能够从你的 package 导入
import os, sys
dir_path = os.path.dirname(os.path.realpath(__file__))
parent_dir_path = os.path.abspath(os.path.join(dir_path, os.pardir))
sys.path.insert(0, parent_dir_path)
I know it's cumbersome but I'm not sure if there's a better solution.我知道这很麻烦,但我不确定是否有更好的解决方案。
I figured out the problem was that I was running the file as a script or my command as a script.我发现问题是我将文件作为脚本运行,或者我的命令作为脚本运行。
python -c "import Sw"
treats "import Sw"
as a script which is why relative and absolute imports weren't working. python -c "import Sw"
将"import Sw"
视为脚本,这就是相对和绝对导入不起作用的原因。 It wasn't treating Sw as part of a package, just a standalone module.它没有将 Sw 视为 package 的一部分,而只是一个独立模块。 This Question cleared things up for me.
这个问题为我解决了问题。 I should have been doing
python -m Switch.Sw
.我应该一直在做
python -m Switch.Sw
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.