【发布时间】:2021-02-08 17:14:06
【问题描述】:
我在构建项目结构时遇到了一些困难。
这是我的项目目录结构:
MusicDownloader/
__init__.py
main.py
util.py
chart/
__init__.py
chart_crawler.py
test/
__init__.py
test_chart_crawler.py
这些是代码:
1.main.py
from chart.chart_crawler import MelonChartCrawler
crawler = MelonChartCrawler()
2.test_chart_crawler.py
from ..chart.chart_crawler import MelonChartCrawler
def test_melon_chart_crawler():
crawler = MelonChartCrawler()
3.chart_crawler.py
import sys
sys.path.append("/Users/Chois/Desktop/Programming/Project/WebScrape/MusicDownloader")
from .. import util
class MelonChartCrawler:
def __init__(self):
pass
4.util.py
def hi():
print("hi")
在MusicDownloader中,当我通过python main.py执行main.py时,报错:
File "main.py", line 1, in <module>
from chart.chart_crawler import MelonChartCrawler
File "/Users/Chois/Desktop/Programming/Project/WebScrape/MusicDownloader/chart/chart_crawler.py", line 4, in <module>
from .. import util
ValueError: attempted relative import beyond top-level package
但是当我通过py.test test_chart_crawler.py在测试目录中执行我的测试代码时,它可以工作
当我第一次面对绝对、相对导入时,它看起来非常简单和直观。但它现在让我发疯。需要你的帮助。谢谢
【问题讨论】:
标签: python python-3.x package pytest