在 bash 脚本中激活 python 虚拟环境失败并显示 "sudo: source: command not found"
Activating a python virtual environment within a bash script fails with "sudo: source: command not found"
我正在尝试使用 Bash 在 Ubuntu 18.04 上自动部署我的 Python-Flask 应用程序,方法是准备所有必要的 files/directories 并从 Github 克隆源代码,然后创建虚拟环境、安装必备模块等
现在因为我必须使用 sudo
执行我的 Bash 脚本,这意味着整个脚本将作为 root
执行,除非我另外指定使用 sudo -u myuser
] 在激活我的虚拟环境时,我得到以下输出: sudo: source: command not found
并且我随后的 pip 安装都安装在虚拟环境之外。我的代码摘录如下:
#!/bin/bash
...
sudo -u "$user" python3 -m venv .env
sudo -u $SUDO_USER source /srv/www/www.mydomain.com/.env/bin/activate
sudo -u "$user" pip install wheel
sudo -u "$user" pip install uwsgi
sudo -u "$user" pip install -r requirements.txt
...
现在对于我来说,如果这有意义的话,我无法弄清楚如何在虚拟环境的上下文中激活虚拟环境。
我搜索了网络,我发现的大多数 questions/answers 都围绕着如何在 Bash 脚本中激活虚拟环境,而不是如何以单独的用户身份激活虚拟环境在作为 sudo
.
执行的 Bash 脚本中
那是因为source
不是可执行文件,而是built-inbash
命令。它不适用于 sudo
,因为后者接受程序名(即可执行文件)作为参数。
P.S。不清楚为什么必须以 root 身份执行整个脚本。如果您只需要以 root 身份执行一些命令(例如 starting/stopping 一项服务)并且 运行 剩下的大多数命令作为普通用户,您可以对这些命令使用 sudo only 。例如。以下脚本
#!/bin/bash
# The `whoami` command outputs the current username. Unlike `source`, this is
# a full-fledged executable file, not a built-in command
whoami
sudo whoami
sudo -u postgres whoami
在我的机器上输出
trolley813
root
postgres
P.P.S。您可能不需要将环境激活为 root
.
我正在尝试使用 Bash 在 Ubuntu 18.04 上自动部署我的 Python-Flask 应用程序,方法是准备所有必要的 files/directories 并从 Github 克隆源代码,然后创建虚拟环境、安装必备模块等
现在因为我必须使用 sudo
执行我的 Bash 脚本,这意味着整个脚本将作为 root
执行,除非我另外指定使用 sudo -u myuser
] 在激活我的虚拟环境时,我得到以下输出: sudo: source: command not found
并且我随后的 pip 安装都安装在虚拟环境之外。我的代码摘录如下:
#!/bin/bash
...
sudo -u "$user" python3 -m venv .env
sudo -u $SUDO_USER source /srv/www/www.mydomain.com/.env/bin/activate
sudo -u "$user" pip install wheel
sudo -u "$user" pip install uwsgi
sudo -u "$user" pip install -r requirements.txt
...
现在对于我来说,如果这有意义的话,我无法弄清楚如何在虚拟环境的上下文中激活虚拟环境。
我搜索了网络,我发现的大多数 questions/answers 都围绕着如何在 Bash 脚本中激活虚拟环境,而不是如何以单独的用户身份激活虚拟环境在作为 sudo
.
那是因为source
不是可执行文件,而是built-inbash
命令。它不适用于 sudo
,因为后者接受程序名(即可执行文件)作为参数。
P.S。不清楚为什么必须以 root 身份执行整个脚本。如果您只需要以 root 身份执行一些命令(例如 starting/stopping 一项服务)并且 运行 剩下的大多数命令作为普通用户,您可以对这些命令使用 sudo only 。例如。以下脚本
#!/bin/bash
# The `whoami` command outputs the current username. Unlike `source`, this is
# a full-fledged executable file, not a built-in command
whoami
sudo whoami
sudo -u postgres whoami
在我的机器上输出
trolley813
root
postgres
P.P.S。您可能不需要将环境激活为 root
.