Python 虚拟环境不适用于我自己的包

Python with virtual evironment not working with my own package

我的项目是这样的:

src
 |--annotation_correction
 |--|--suggestion.py
 |--|--error.py
 |--|--...
venv
 |--...

我在主文件夹中使用 pip install -e . 安装了我的包。 当我键入 pip freeze 时,我的包“annotation”在列表中并且 VSCode 似乎也将其识别为已安装的包。

问题是当我 运行 suggestion.py 试图导入例如从 error.py 到 from annotation_correction.error import Error, ErrorType,我仍然得到错误:
ModuleNotFoundError: No module named 'annotation_correction.error'; 'annotation_correction' is not a package

所有这一切都是在使用 运行ning 的解释器时完成的。

我的 setup.py 只调用 setup() 而我的 setup.cfg 看起来像这样:

...
packages = 
    annotation_correction
...
package_dir =
    =src

让我的评论成为答案:

如果您的包中有一个模块使用 from package import modulefrom . import module 或类似的方式从同一个包导入其他模块,那么您将需要使用 the -m switch:

Search sys.path for the named module and execute its contents as the __main__ module.

否则,Python 将设置 sys.path,因此 运行 脚本的目录在其中,这自然会对导入造成严重破坏(因为包是“隐形”)。

这表示您是否安装了一个包(实际上您不一定需要 pip install -e 您正在使用的相同包)。

另一种选择是在包外有一个独立的脚本作为入口点,例如from annotation_correction.suggestion import main(因为从那个脚本的角度来看,包在那里,一切都很好——如果安装了包,-e 或没有 -e,脚本甚至没有需要在包目录旁边,因为包已经安装在搜索路径中),但这是不必要的。

Visual Studio 代码显然 supports the same thing with a "module" run configuration.