[英]Python ModuleNotFoundError when importing a package
I getting and error when I try to import a package from another folder.当我尝试从另一个文件夹导入 package 时出现错误。 I have the folowing:
我有以下内容:
project
|
|-- main.py
|
|-- lib
| |-- __init__.py
| |-- main_class.py
| |-- global_functions.py
| |-- cg_api_simple
| |-- cg_api_status
|
|-- tests
|-- __init__.py
|-- test_main_class.py
Where my lib/__init__.py
has:我的
lib/__init__.py
有:
from lib.main_class import PyGecko
and my test/__init__.py
is empty.我的
test/__init__.py
是空的。
When I run python3 -m unittest test_main_class.py
I get:当我运行
python3 -m unittest test_main_class.py
我得到:
======================================================================
ERROR: test_main_class (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: test_main_class
Traceback (most recent call last):
File "/usr/lib/python3.8/unittest/loader.py", line 154, in loadTestsFromName
module = __import__(module_name)
File "/home/someone/Documents/pythoncoingecko/tests/test_main_class.py", line 1, in <module>
from lib import PyGecko
ModuleNotFoundError: No module named 'lib'
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (errors=1)
I've already tried:我已经尝试过:
__init__.py
from both folders__init__.py
The only time I don't get an error is when I move test_main_class.py
to where main.py is located.我唯一没有收到错误的时间是将
test_main_class.py
移动到 main.py 所在的位置。 How could I solve this?我该如何解决这个问题? You can see more on github
你可以在github上看到更多
https://github.com/SrJMaia/pythoncoingecko
https://github.com/SrJMaia/pythoncoingecko
Thanks谢谢
All you need is a proper combination of your current working directory, the PYTHONPATH
environment variable and the path to the test.您所需要的只是当前工作目录、
PYTHONPATH
环境变量和测试路径的适当组合。
If you run python3 -m unittest test_main_class.py
from the tests
directory, you need to add the project
directory to PYTHONPATH
.如果从
tests
目录运行python3 -m unittest test_main_class.py
,则需要将project
目录添加到PYTHONPATH
。 Ie: IE:
$ PYTHONPATH=.. python3 -m unittest test_main_class.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
$ PYTHONPATH=/tmp/project python3 -m unittest test_main_class.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
Or you can run python3 -m unittest tests/test_main_class.py
from the project
directory.或者您可以从
project
目录运行python3 -m unittest tests/test_main_class.py
。 In that case, you do not need to modify PYTHONPATH
.在这种情况下,您不需要修改
PYTHONPATH
。 Ie IE
$ python3 -m unittest tests/test_main_class.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.