python - 尝试从另一个仓库(在 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'.
我做了一些研究并意识到我需要做任何一个:我需要制作一个包裹吗?还是我需要添加到模块路径导入语句?
提前致谢。
解决方案
如果您决定使用包,您可以在 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
推荐阅读
- c# - C# EF6 条件属性选择?
- ruby-on-rails - jelastic 中的 rake_deploy 如何与 ENV 配合使用
- javascript - 为脚本调用创建切换按钮
- android - Android ScrollView 两侧垂直滚动条
- ios - 如何快速获得 iphone X 键盘的真实尺寸?
- vba - VBA 溢出行为
- python-3.x - 将 numba 与 time.clock() 和 timeit 一起使用
- python - tf.nn.softmax_cross_entropy_with_logits_v2 为 MLP 返回零
- ruby - 迭代器不包括在循环内添加到它的值
- excel - 如何在 pytest excel 报告中添加测试步骤中的值