[英]Activating a python virtual environment within a bash script fails with “sudo: source: command not found”
I'm trying to automate the deployment of my Python-Flask app on Ubuntu 18.04 using Bash by going through the motion of preparing all the necessary files/directories and cloning the source code from Github followed by creating the virtual environment, installing the pre-requisite modules and etc. 我正在尝试通过准备所有必需的文件/目录并从Github克隆源代码,然后创建虚拟环境,安装预安装版本的操作,使用Bash在Ubuntu 18.04上自动将Python-Flask应用程序部署在Bash上。必要的模块等
Now because I have to execute my Bash script using sudo
, this means that the entire script will be executed as root
except where I specify otherwise using sudo -u myuser
and when it comes to activating my virtual environment, I get the following output: sudo: source: command not found
and my subsequent pip installs are all installed outside of the virtual environment. 现在,因为我必须使用
sudo
执行我的Bash脚本,这意味着整个脚本将以root
身份执行,除非我使用sudo -u myuser
指定,否则在激活我的虚拟环境时,我将得到以下输出: sudo: source: command not found
,后续的pip安装都安装在虚拟环境之外。 Excerpts of my code below: 我的代码摘录如下:
#!/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
...
Now for the life of me, I can't figure out how to activate the virtual environment in the context of the virtual environment if this makes any sense. 现在,对于我来说,如果有任何意义,我想不通如何在虚拟环境的上下文中激活虚拟环境。
I've scoured the web and most of the questions/answers I found revolves around how to activate the virtual environment in a Bash script but not how to activate the virtual environment as a separate user within a Bash script that was executed as sudo
. 我在网上进行了搜索,发现的大多数问题/答案都围绕着如何在Bash脚本中激活虚拟环境,而不是如何在以
sudo
执行的Bash脚本中作为单独的用户激活虚拟环境。
That's because source
is not an executable file, but a built-in bash
command. 这是因为
source
不是可执行文件,而是内置的bash
命令。 It won't work with sudo
, since the latter accepts a program name (ie executable file) as argument. 它不能与
sudo
,因为sudo
接受程序名称(即可执行文件)作为参数。
PS It's not clear why you have to execute the whole script as root. PS尚不清楚为什么必须以root用户身份执行整个脚本。 If you need to execute only a number of commands as root (eg for starting/stopping a service) and run a remaining majority as a regular user, you can use sudo only for these commands .
如果您仅需要以root身份执行多个命令(例如,用于启动/停止服务)并以普通用户身份运行其余大多数命令,则只能对这些命令使用sudo。 Eg the following script
例如以下脚本
#!/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
on my machine outputs 在我的机器输出上
trolley813
root
postgres
PPS You probably don't need to activate an environment as root
. PPS您可能不需要以
root
身份激活环境。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.