簡體   English   中英

Python:ImportError:嘗試在沒有已知父項的情況下進行相對導入 package

[英]Python: ImportError: attempted relative import with no known parent package

我有一個非常簡單的 python 項目:

sample/__init__.py
sample/main.py
tests/test_sample.py

main.py包含:

def echo_the_arg(the_arg):
    return the_arg

test_sample.py包含:

import unittest
from sample.main import echo_the_arg

class SampleTest (unittest.TestCase):
    def test_echo_the_arg(self):
        assert echo_the_arg(1) == 1

我的 IDE 解析sample.main模塊 OK:

在此處輸入圖像描述

但是當我嘗試通過發出pytest tests從項目的根目錄運行測試時,我收到一個錯誤:

ImportError while importing test module '/Users/me/python-project-template/tests/test_sample.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/usr/local/Cellar/python@3.9/3.9.2_4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py:127: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
tests/test_sample.py:2: in <module>
    from sample.main import echo_the_arg
E   ModuleNotFoundError: No module named 'sample'

我已經仔細閱讀了很多關於 SO 的搜索結果,這些結果與這樣的相對進口有關,但我對為什么我會遇到這種失敗一無所知。 為什么pytest找不到我的sample模塊?


更新,我發現我可以通過運行python -m pytest tests

platform darwin -- Python 3.9.2, pytest-6.2.4, py-1.10.0, pluggy-0.13.1
rootdir: /Users/me/python-project-template
collected 1 item                                                                                                                                                                                          

tests/test_sample.py .                                                                                                                                                                              [100%]

======================= 1 passed in 0.02s =======================

所以我想知道為什么從命令行運行pytest會失敗。

我想到了。 我需要添加一個額外的(空的) __init__.py文件。 所以我的結構現在看起來像這樣:

sample/__init__.py
sample/main.py
tests/__init__.py
tests/test_sample.py

Output:

(venv) ➜  python-project-template git:(master) ✗ pytest tests          
=========================================================================================== test session starts ===========================================================================================
platform darwin -- Python 3.9.2, pytest-6.2.4, py-1.10.0, pluggy-0.13.1
rootdir: /Users/me/python-project-template
collected 1 item                                                                                                                                                                                          

tests/test_sample.py .                                                                                                                                                                              [100%]

======================= 1 passed in 0.02s =======================

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM