修改运行Python子进程时的环境变量

问题描述 投票:0回答:1

我正在尝试在与默认环境不同的虚拟环境中运行 Python 子进程。我的解决方案基于这个答案。我的剧本是

import os
import subprocess
from pathlib import Path
from icecream import ic

VIRTUAL_ENV = str(Path(Path.home(), '.pyenv/versions/wx'))

script_path = 'scripts/foo'
script_env = os.environ.copy()
script_env["VIRTUAL_ENV"] = VIRTUAL_ENV
ic(os.environ['VIRTUAL_ENV'])
ic(script_env['VIRTUAL_ENV'])
subprocess.run([script_path], env=script_env)

其中 foo 调用需要 virtualenv wx 的 Python 程序。 script_env['VIRTUAL_ENV'] 是正确的,但是我收到错误

激活 virtualenv 失败。 也许 pyenv-virtualenv 尚未正确加载到您的 shell 中。 请重新启动当前 shell 并重试。

python subprocess
1个回答
0
投票

执行脚本之前需要激活虚拟环境。此代码将激活虚拟环境(如果存在),在环境中执行提供的脚本,然后将其停用。

import subprocess
import os

def run_subprocess_in_virtualenv(virtual_env_path, python_script):
    # Path to the virtual environment's activate script
    venv_activate = f"{virtual_env_path}/bin/activate"
    
    
    # Check if the virtual environment activate script exists
    if not os.path.exists(venv_activate):
        print(f"Virtual environment not found at {venv_activate}. Please check the path.")
        return
    
    try:
        # Activate the virtual environment
        activate_cmd = f"source {venv_activate}"
        subprocess.run(activate_cmd, shell=True, check=True)
        
        # Run script within the virtual environment
        python_cmd = f"{virtual_env_path}/bin/python {python_script}"
        subprocess.run(python_cmd, shell=True, check=True)
        
    except subprocess.CalledProcessError as e:
        print(f"Error occurred while running subprocess: {e}")
    
    finally:
        # Deactivate the virtual environment
        deactivate_cmd = "deactivate"
        subprocess.run(deactivate_cmd, shell=True)


# Run the script
venv_path = "/path/to/your/virtualenv"
script_path = "scripts/foo.py"
run_subprocess_in_virtualenv(venv_path, script_path)

© www.soinside.com 2019 - 2024. All rights reserved.