简体   繁体   English

Python 激活并保持打开 Virtualenv 的脚本

[英]Python script to activate and keep open a Virtualenv

I need a python script that will activate a virtualenv, run another python program inside the virtualenv, and then close the virutalenv after the second python program closes.我需要一个 python 脚本来激活 virtualenv,在 virtualenv 中运行另一个 python 程序,然后在第二个 python 程序关闭后关闭 virutalenv。 Here is my code:这是我的代码:

import os
import subprocess
from subprocess import Popen

activate_dir = "C:/Users/JohnDoe/theprogram/Scripts/"
os.chdir(activate_dir)
subprocess.Popen(["activate.bat"])

cal_dir = "C:/Users/JohnDoe/theprogram/"
os.chdir(cal_dir)
os.system('python program_file.py')

However, when this code run, I get an import error from the program_file which means the virtualenv is not activated.然而,当这段代码运行时,我从program_file中得到一个导入错误,这意味着 virtualenv 没有被激活。 How can I fix this?我怎样才能解决这个问题?

Thanks谢谢

Edit: This is on a Windows environment.编辑:这是在 Windows 环境中。

The issue is that you are creating a new process with subprocess.Popen(["activate.bat"]) that is using that virtual environment, you're not changing your environment. 问题是您正在使用subprocess.Popen([“activate.bat”])创建一个新进程,该进程正在使用该虚拟环境,您不会更改您的环境。 What you need to do is to either call the python script in the same process you span: 你需要做的是在你跨越的同一个过程中调用python脚本:

os.system("source activate;python -V")

Or you could write a shell script that starts the virtual environment and calls any python script you send to it. 或者你可以编写一个shell脚本来启动虚拟环境并调用你发送给它的任何python脚本。 In bash (on linux) this would be: 在bash(在linux上)这将是:

#!/bin/bash
# start a virtual environment and call a python module
# usage: ./runVirenvPythonModule module.py
source activate
python $1 # this is the first cmd line argument passed in

I've found a method to detect, activate, and create (if needed) a virtual environment inside a Python script and run inside that virtual environment while remaining inside that script and without the use of shell commands issued from that script (except to display installed packages via pip list ).我找到了一种方法来检测、激活和创建(如果需要)Python 脚本中的虚拟环境并在该虚拟环境中运行,同时保留在该脚本中并且不使用从该脚本发出的 shell 命令(除了显示通过pip 列表安装的软件包)。 Without the use of shell commands, the script becomes OS agnostic.如果不使用 shell 命令,脚本将与操作系统无关。

Here is some example code.这是一些示例代码。 You simply run it from whatever OS shell you are using (Windows, Linux, MacOS):您只需从您使用的任何操作系统 shell 运行它(Windows、Linux、MacOS):

import os
import sys
import venv

def isvirtualenv():
    return sys.prefix != sys.base_prefix

def findfile(startdir, pattern):
    for root, dirs, files in os.walk(startdir):
        for name in files:
            if name.find(pattern) >= 0:
                return root + os.sep + name

    return None

venv_path = 'venv'            # This is an example path

if isvirtualenv():
    print('Already in virtual environment.')
else:
    if findfile(os.getcwd(), 'activate') is None:
        print('No virtual environment found. Creating one.')
        env = venv.EnvBuilder(with_pip = True)
        env.create(venv_path)
    else:
        print('Not in virtual environment. Virtual environment directory found.')

    # This is the heart of this script that puts you inside the virtual environment. 
    # There is no need to undo this. When this script ends, your original path will 
    # be restored.
    os.environ['PATH'] = os.path.dirname(findfile(os.getcwd(), 'activate')) + os.pathsep + os.environ['PATH']
    sys.path.insert(1, os.path.dirname(findfile(venv_path, 'easy_install.py')))

# Run your script inside the virtual environment from here
print(os.environ['PATH'])
os.system('pip list')

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM