我最近对Python中的虚拟环境感兴趣,以使我的代码更有组织性和可移植性.因此,我对Raspberry Pi进行了工厂重置,并从头开始,只使用默认的Python模块.在此之前,我列出了我的项目及其版本的所有依赖项,并将它们安装到了一个新创建的虚拟环境中.这是我在终端中如何做到这一点的示例,从我的项目目录开始.(我希望这与这个问题有关).

millertime@raspberrypi:~/Desktop/Project $ python3 -m venv venv
millertime@raspberrypi:~/Desktop/Project $ source venv/bin/activate
(venv) millertime@raspberrypi:~/Desktop/Project $ pip3 install mutagen==1.45.1
Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
Collecting mutagen==1.45.1
  Using cached https://www.piwheels.org/simple/mutagen/mutagen-1.45.1-py3-none-any.whl (218 kB)
Installing collected packages: mutagen
Successfully installed mutagen-1.45.1
(venv) millertime@raspberrypi:~/Desktop/Project $ deactivate

我的main.py文件和我的虚拟环境在同一个目录中,但是当我try 导入我在虚拟环境中安装的一个模块时,我得到了一个错误.

Traceback (most recent call last):
  File "/home/millertime/Desktop/Project/test.py", line 1, in <module>
    import mutagen
ModuleNotFoundError: No module named 'mutagen'

除了Pygame和Pillow之外,我在虚拟环境中放置的所有其他库都会发生同样的情况.我认为这是因为Python预装了不同的版本.此外,我可以导入操作系统、随机和Python中全局安装的任何其他内容.

这就引出了一个问题,如何允许python程序导入虚拟环境中包含的模块?我在Raspberry Pi 4上使用Python 3.9.

推荐答案

为了使用虚拟环境,您应该按顺序执行以下步骤:

  1. 创建VENV
  2. 来源venv/bin/activate
  3. 将所需的模块安装到VENV上
  4. 调用脚本
  5. 停用VENV

我已经在我的VENV中测试了mutagen模块,它按预期工作.

The used commands whit some commands:

# 创建VENV
>>> python3 -m venv venv

# Sourcing the "activate" file.
>>> source venv/bin/activate

# Verify if the Python is used from VENV.
>>> which python3
/repo/user/venv/bin/python3

# Install the "mutagen" module to VENV.
>>> pip3 install mutagen==1.45.1
Collecting mutagen==1.45.1
  Downloading https://files.pythonhosted.org/packages/16/b3/f7aa8edf2ff4495116f95fd442b2a346aa55d1d46313143c8814886dbcdb/mutagen-1.45.1-py3-none-any.whl (218kB)
    100% |████████████████████████████████| 225kB 7.3MB/s 
Installing collected packages: mutagen
Successfully installed mutagen-1.45.1
You are using pip version 10.0.1, however version 21.3.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

# Try to use the "mutagen" in the console (It worked perfectly).
>>> python3
Python 3.6.6 (default, Aug 24 2018, 09:30:17) 
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import mutagen

# 停用VENV (After this the Python will be used from OS not from VENV)
>>> deactivate

Python相关问答推荐

Python—压缩叶 map html作为邮箱附件并通过sendgrid发送

关于两个表达式的区别

从嵌套极轴列的列表中删除元素

在第一次调用时使用不同行为的re. sub的最佳方式

随机森林n_估计器的计算

用0填充没有覆盖范围的垃圾箱

正在try 让Python读取特定的CSV文件

极点用特定值替换前n行

为什么在不先将包作为模块导入的情况下相对导入不起作用

如何在Polars中将列表中的新列添加到现有的数据帧中?

当lambda函数作为参数传递时,pyo3执行

Python:使用asyncio.StreamReader.readline()读取长行

如何在networkx图中提取和绘制直接邻居(以及邻居的邻居)?

如何将ManyToManyfield用于Self类

Pandas:新列,从列表中采样,基于列值

如何让doctest在mkdocs的标记代码块中运行示例?

如何动态修改气流任务decorator 属性?

如何生成一个区间的均匀分布的子区间?

巨 Python 品脱摄氏度单位

解析类型的字符串表示形式以获取子项的类型