简体   繁体   English

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

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

Here's what I would like to do with my Python script:这是我想用我的 Python 脚本做的事情:

  1. Create virtual environment创建虚拟环境
  2. Change directory into environment将目录更改为环境
  3. Activate environment激活环境
  4. Install django安装 django
  5. Do other stuff...做点别的...

I've managed to create the environment and change directory with the following:我已经设法创建环境并使用以下内容更改目录:

import subprocess
import os

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

But activating the environment is a different story:但是激活环境是另一回事:

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

Result:结果:

FileNotFoundError: [WinError 2] The system cannot find the file specified FileNotFoundError: [WinError 2] 系统找不到指定的文件

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

Result:结果:

PermissionError: [WinError 5] Access is denied PermissionError: [WinError 5] 访问被拒绝

Just to clarify, I made sure I was in the correct directory by using print(os.getcwd()).澄清一下,我使用 print(os.getcwd()) 确保我在正确的目录中。

After this I'd then like to install django. I think it has to happen inside the same run() method like so:在此之后我想安装 django。我认为它必须在同一个 run() 方法中发生,如下所示:

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

Is this even possible?这可能吗?

There is a number of things wrong here.这里有很多错误。 When you run a subprocess, the environment it creates disappears when the subprocess exits.当您运行子进程时,它创建的环境会在子进程退出时消失。

What you can do is wrap Python inside Python, something like可以做的是将 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
    """])

which of course is just a rather pointless complication, and better written as a shell script.这当然只是一个毫无意义的并发症,最好写成 shell 脚本。

#!/bin/bash

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

Original poster here.原贴在这里。 I just want to expand on triplee 's answer above by displaying the full code required to achieve my desired result.我只想通过显示实现我想要的结果所需的完整代码来扩展上面的triplee的答案。

Python Script #1 - django-setup 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 Script - intermediary.sh Shell 脚本- intermediary.sh

#!/bin/bash

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

Python Script #2 - django-setup-2 Python 脚本 #2 - django-setup-2

#!/usr/bin/env python

import subprocess

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

Executing the command django-setup blog would achieve the following result:执行命令django-setup blog会得到如下结果:

env_blog/
    Scripts/
    Include/
    Lib/
    blog/
        config/
        manage.py
    pyvenv.cfg
  1. For the creation of a virtual environment and using it, follow here .要创建和使用虚拟环境,请按照此处进行操作。

  2. Alternatively, you may use Conda to create and manage your virtual environments.或者,您可以使用Conda来创建和管理您的虚拟环境。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何激活Python虚拟环境并同时执行脚本? - How to activate a Python virtual environment and execute a script at the same time? 如何在Mac上的bash脚本中激活Python虚拟环境并启动python脚本? - How can I activate a Python virtual environment and launch a python script, in a bash script on Mac? 如何在使用脚本的调试模式(Linux机器)时在pycharm中激活wsl中的虚拟环境 - How Can I activate virtual environment in wsl in pycharm while using debug mode of a script (Linux machine) 从 python 脚本激活虚拟环境 - Activate virtual environment from a python script 如何在python shell中激活虚拟环境 - how can I activate virtual environment in python shell 如何从bash脚本中临时绕过python虚拟环境? - How can I temporary bypass python virtual environment from inside a bash script? 如何从不同的 repo 激活 python 虚拟环境? - How do I activate python virtual environment from a different repo? 为什么我无法使用“source env/bin/activate”命令激活我的虚拟 Python 环境? - How come I can not activate my Virtual Python Environment with 'source env/bin/activate' command? 如何在当前虚拟环境中运行可执行的python脚本? - How can I make an executable python script run inside the current virtual environment? Visual Code 如何自动激活虚拟环境? - Visual Code how can I activate the virtual environment automatically?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM