[英]I tried to run a python script, but got ImportError: attempted relative import with no known parent package
I found other stackoverflow questions and answers for this error, but none of them worked for me.我找到了有关此错误的其他 stackoverflow 问题和答案,但没有一个对我有用。 My python package problem:
我的 python package 问题:
I tried to install packages with these commands so I could run tests:我尝试使用这些命令安装软件包,以便可以运行测试:
$ pip3 install virtualenv
$ virtualenv -p $(which python3.9) venv
$ source venv/bin/activate
$ pip install --upgrade pip # stop local environments from messing things up
$ pip install -r path/to/requirements.txt
I tried to run my tests:我试图运行我的测试:
$ python -m unittest discover
I got this error:我收到了这个错误:
======================================================================
ERROR: some_file (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: some_file
Traceback (most recent call last):
File "/usr/local/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 436, in _find_test_path
module = self._get_module_from_name(name)
File "/usr/local/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 377, in _get_module_from_name
__import__(name)
File "/Users/path/some_file.py", line 3, in <module>
from .other_file import some_function, SomeClass
ImportError: attempted relative import with no known parent package
----------------------------------------------------------------------
As the error said, I was trying to use a relative path in my file:正如错误所说,我试图在我的文件中使用相对路径:
from .other_file import some_function, SomeClass
I don't know about other versions of python, but I expected this to be possible in python3.我不知道 python 的其他版本,但我希望这在 python3 中是可能的。
I needed to add this line to my installation commands:我需要将此行添加到我的安装命令中:
$ pip install --editable .
That is:那是:
$ pip3 install virtualenv
$ virtualenv -p $(which python3.9) venv
$ source venv/bin/activate
$ pip install --upgrade pip # stop local environments from messing things up
$ pip install -r path/to/requirements.txt
$ pip install --editable .
I don't yet understand why it works.我还不明白为什么它会起作用。 I'll update this answer if I find out more.
如果我发现更多,我会更新这个答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.