首页 > 解决方案 > 尝试从另一个仓库(在 VSCode 中)导入 Python 模块

问题描述

目前有两个 repos 克隆到 VSCode 上。当我打开 VSCode 时,我的目录结构如下所示:

- Repo1
  - Base 1
    - Scripts
      -Code.py
- Repo2
  - testcode.py

我尝试执行的这个 python 文件具有以下导入语句:

from repo2.testcode import testmodule

但是,python 没有将其识别为模块......并且正在返回以下错误消息:

 ModuleNotFoundError: No Module named 'Repo2'.

我做了一些研究并意识到我需要做任何一个:我需要制作一个包裹吗?还是我需要添加到模块路径导入语句?

提前致谢。

标签: pythonpython-3.xvisual-studio-code

解决方案


如果您决定使用包,您可以在 setup.py 中指定另一个本地包的路径。

您的整体结构将是:

|-- Repo1/
|   |-- setup.py
|   |-- Repo1/
│   |    |-- __init__.py
|   |    |--Code.py
|   |-- tests/
|   |    |--test_Code.py
|
|-- Repo2/
|   |-- setup.py
|   |-- Repo2/
│   |    |-- __init__.py
|   |    |--testcode.py

回购 1/setup.py。

from setuptools import setup, find_packages
import os

# dynamically determine the path to Repo2
local_name = "Repo2"
local_path = os.getcwd().split(os.sep)
local_path = os.sep.join(local_path[0:local_path.index(local_name)])
local_path = os.path.join(local_path, local_name)


setup(
    name="Repo1",
    version="1.0.0",
    description="First Repo",
    python_requires=">=3.5.0",
    packages = find_packages(),
    install_requires=[
        'SomePyPIPackage',
        f"{local_name} @ file://localhost/{local_path}#egg={local_name}"
    ]
)

Repo2 中的 setup.py 文件类似,但没有 install_requires localhost 部分。

然后,当您在 Repo1 的顶级目录中时,您可以运行(不要忘记最后的点):

# would have to reinstall if you make changes to Repo2
pip install .

# or install in editable mode
pip install -e .

然后在 Repo1 你应该能够使用:

from repo2.testcode import testmodule

推荐阅读