如何从 shell 脚本进入 Python 虚拟环境并在其中执行 运行 shell 命令?

How does one enter a Python virtual environment and run shell commands in it from a shell script?

我已经在 CentOS 7 Docker 容器中编写 shell 脚本 运行 以创建 AppImage。在此脚本中,我想从 Python 虚拟环境(由 运行ning source AppDir/usr/bin/activate 启动)中 运行 Shell 命令 pip install -U spyder 启动通过 shell 脚本。问题是我不知道该怎么做,因为脚本中 source AppDir/usr/bin/activate 行之后的行被忽略了(因为此时在脚本中,shell 已进入 Python 虚拟环境)。那么是否有一些选项我需要传递 source AppDir/usr/bin/activate 命令,以便它会 运行 这个 Python 虚拟环境中的 pip install -U spyder 命令?

您可以在不激活虚拟环境的情况下安装您的要求,但需要提供您的 virtualenv 的完整路径 pip

<path_to_virtualenv>/bin/pip install -U spyder

因为 activate 正在做的是将您的 virtualenv bin/ 文件夹放在 PATH 之前,这样 pippython 命令将引用到你的 viartualenv 在全球之前。来自 activate 的来源:

VIRTUAL_ENV="<path_to_env>"
export VIRTUAL_ENV

_OLD_VIRTUAL_PATH="$PATH"
PATH="$VIRTUAL_ENV/bin:$PATH"
export PATH