[英]Activate virtual environment and install requirements in the first setup automatically - Python, Windows
I want to write a first_setup.py script, where users can run it for the first time and the script will do the entire setup automatically, namely it will create a virtual environment, activate it, and install the requirements with pip. Users can then start to use the program without worrying about any dependency issue.我想写一个 first_setup.py 脚本,用户可以在第一次运行它,脚本会自动完成整个设置,即它会创建一个虚拟环境,激活它,并使用 pip 安装要求。用户然后可以开始使用该程序而不用担心任何依赖性问题。
Therefore, I used venv together with subprocess library.因此,我将 venv 与 subprocess 库一起使用。 My Python version is 3.7.5.我的Python版本是3.7.5。 With the following command, it creates the virtual environment in the working directory:使用以下命令,它会在工作目录中创建虚拟环境:
env_name = ".venv"
subprocess.run(["python", "-m", "venv", env_name])
However, activation doesn't work.但是,激活不起作用。 I tried to activate it in various ways, for example:我尝试以各种方式激活它,例如:
subprocess.run([f"{venv_name}\\Scripts\\Activate.ps1"], shell=True)
This just opens Activate.ps1 in Windows Text Editor like a.txt file (?).这只会在 Windows 文本编辑器中打开 Activate.ps1,如 .txt 文件 (?)。 I also thought to add.../Scripts/python.exe to the PATH variable, but it didn't work actually.我还想将.../Scripts/python.exe 添加到 PATH 变量中,但实际上并没有用。
Furthermore, when the venv created by the script, VS Code pops up a message saying a venv detected, do you want to use it?此外,当脚本创建 venv 时,VS Code 会弹出消息说检测到 venv,是否要使用它? If I click on Yes, then it changes my interpreter to venv, which is exactly what I want to do, but automatically with the first_setup.py script.如果我单击“是”,它会将我的解释器更改为 venv,这正是我想要做的,但会自动使用 first_setup.py 脚本。
How can I proceed?我该如何进行?
Does this first_setup script need to be Python?这个 first_setup 脚本需要是 Python 吗?
The problem is that the activate script sets environment variables for the shell, which is why it's usually run with 'source'.问题在于激活脚本为 shell 设置了环境变量,这就是它通常与“源”一起运行的原因。
try using bash file:尝试使用 bash 文件:
python3 -m venv venv
source venv/bin/activate
pip install your_library
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.