如何从 python 脚本激活虚拟环境并在其中执行进一步的指令?

How can I activate the virtual environment from a python script and execute further instructions while inside of it?

这是我想用我的 Python 脚本做的事情:

  1. 创建虚拟环境
  2. 将目录更改为环境
  3. 激活环境
  4. 安装 django
  5. 做其他事情...

我已经成功创建了环境并更改了以下目录:

import subprocess
import os

env_name = "env_new"
subprocess.run(["py", "-m", "venv", env_name])
chdir(env_name)

但激活环境是另一回事:

subprocess.run(["source", "./Scripts/activate"])  # Also tried with activate.bat

结果:

FileNotFoundError: [WinError 2] The system cannot find the file specified

subprocess.run([".", "./Scripts/activate"])  # Also tried with activate.bat

结果:

PermissionError: [WinError 5] Access is denied

澄清一下,我使用 print(os.getcwd()).

确保我在正确的目录中

之后我想安装 django。我认为它必须在相同的 运行() 方法中发生,如下所示:

subprocess.run([".", "./Scripts/activate", "&&", "pip", "install", "django"])  # Or something...

这可能吗?

  1. 虚拟环境的创建和使用请参考here

  2. 或者,您可以使用 Conda 来创建和管理您的虚拟环境。

这里有很多错误。当您 运行 子进程时,它创建的环境会在子进程退出时消失。

可以做的是将Python包裹在Python里面,比如

import subprocess

env_name = "env_new"
subprocess.run(["py", "-m", "venv", env_name])

subprocess.run(["%s/bin/python" % env_name, "-c", """
    the rest of your Python code here
    """])

这当然只是一个毫无意义的并发症,最好写成 shell 脚本。

#!/bin/bash

py -m venv env_new
. ./env_new/Scripts/activate
pip install -r requirements.txt
python ./your_real_script_here.py

原始海报在这里。我只想通过显示实现我想要的结果所需的完整代码来扩展上面 triplee 的回答。

Python 脚本 #1 - django-setup

#!/usr/bin/env python
import subprocess
import sys

if __name__ == '__main__':
    if len(sys.argv) > 1:
        subprocess.call(f"intermediary.sh {sys.argv[1]}", shell=True)
    else:
        print("No arguments given")

Shell 脚本 - intermediary.sh

#!/bin/bash

py -m venv "env_"
cd "env_"
. ./Scripts/activate
pip install django
mkdir ""
cd ""
django-setup-2

Python 脚本 #2 - django-setup-2

#!/usr/bin/env python

import subprocess

subprocess.run(['django-admin', 'startproject', 'config', '.'])
print("More code here!")

执行命令django-setup blog会得到如下结果:

env_blog/
    Scripts/
    Include/
    Lib/
    blog/
        config/
        manage.py
    pyvenv.cfg