这不是我第一次遇到这种奇怪的无法解释的现象,无法识别终端中的包并在 PyCharm 中被识别,反之亦然。
我有一个如下所示的目录:
ticklab
├── __init__.py
├── extractors
│ ├── __init__.py
│ ├── base_extractor.py
│ ├── extract.py
│ ├── polygon_cli.py
│ ├── polygon_extractor.py
│ └── stocks_debug.txt
└── logs
└── extraction_session.log
在polygon_extractor.py
我需要从中导入BaseExtractor
,base_extractor
所以我这样做:
from extractors.base_extractor import BaseExtractor
它在 PyCharm 中运行得非常好但是当我在提取器目录中执行此操作时
emadboctor@MacBook-Pro extractors % python3 polygon_extractor.py
Traceback (most recent call last):
File "polygon_extractor.py", line 1, in <module>
from extractors.base_extractor import BaseExtractor
ModuleNotFoundError: No module named 'extractors'
所以我在main
保护下添加了这个并从 PyCharm 运行
print(os.getcwd())
输出:
/Users/emadboctor/Desktop/Code/ticklab
所以我从终端尝试了这个:
emadboctor@MacBook-Pro ticklab % python3 extractors/polygon_extractor.py
Traceback (most recent call last):
File "extractors/polygon_extractor.py", line 1, in <module>
from extractors.base_extractor import BaseExtractor
ModuleNotFoundError: No module named 'extractors'
emadboctor@MacBook-Pro ticklab %
通过将导入语句更改为:
from base_extractor import BaseExtractor
它在 PyCharm 和终端中运行,但 PyCharm 代码检查无法解决base_extractor
当我将导入语句更改为:
from .base_extractor import BaseExtractor
它在 PyCharm 中解析并运行良好,但在终端中出现以下错误:
Traceback (most recent call last):
File "polygon_extractor.py", line 1, in <module>
from .base_extractor import BaseExtractor
ImportError: attempted relative import with no known parent package
另一种解决方案是添加sys.path.append('..')
但也是解决问题的不干净的解决方案。