简体   繁体   English

Python:如何在临时目录创建虚拟环境并使用 pip 安装模块

[英]Python: How to create a virtual environment at temp dir and install modules with pip

I want to create a temp file and write a python script.我想创建一个临时文件并编写一个 python 脚本。 I want to create a virtual environment at this temp dir and use pip and then run this script with the virtual environment.我想在这个临时目录创建一个虚拟环境并使用 pip 然后在虚拟环境中运行这个脚本。

import pathlib
import tempfile 
import venv

temp = tempfile.TemporaryDirectory()

virtualenv = venv.EnvBuilder(system_site_packages=false)
virtualenv.create(temp.name)

# how could I activate the virtual environment and install the pip module?

with open(pathlib.Path(temp.name)/"run.py", "w") as f:
    f.write("#/usr/bin/env python\n\n")
    f.write("import requests\n")

p = subprocess.run(["python", temp.name", "run.py"])

I believe the following should achieve your expectations:我相信以下内容应该可以达到您的期望:

#!/usr/bin/env python3

import pathlib
import string
import subprocess
import tempfile
import venv

SCRIPT_TEMPLATE = '''\
#!${venv_executable}

import requests
print(requests)
'''

class EnvBuilder(venv.EnvBuilder):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.context = None

    def post_setup(self, context):
        self.context = context

def main():
    with tempfile.TemporaryDirectory() as target_dir_path:
        print(f" *** Created temporary directory '{target_dir_path}'.")
        #
        print(f" *** Creating virtual environment...")
        venv_builder = EnvBuilder(with_pip=True)
        venv_builder.create(str(target_dir_path))
        venv_context = venv_builder.context
        #
        requirements = [
            'requests',
        ]
        print(f" *** Installing {requirements}...")
        pip_install_command = [
            venv_context.env_exe,
            '-m',
            'pip',
            'install',
            *requirements,
        ]
        subprocess.check_call(pip_install_command)
        #
        print(" *** Generating script...")
        script_substitutions = {
            'venv_executable': venv_context.env_exe,
        }
        script = (
            string.Template(SCRIPT_TEMPLATE).substitute(script_substitutions)
        )
        print(" *** Generated script:")
        print("'''")
        print(script)
        print("'''")
        #
        script_path = pathlib.Path(target_dir_path).joinpath('run.py')
        print(f" *** Writing script '{script_path}'")
        script_path.write_text(script)
        #
        print(" *** Executing script...")
        script_command = [
            venv_context.env_exe,
            str(script_path),
        ]
        subprocess.check_call(script_command)

if __name__ == '__main__':
    main()

暂无
暂无

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

相关问题 如何使用 Pip (OS X) 在虚拟环境中安装 Python 包 - How to install a Python package inside a virtual environment with Pip (OS X) 如何在 python 中激活虚拟环境时使用 pip 安装 - How to use pip install while activating virtual environment in python 如何将 python 模块从源安装到虚拟环境 - How to install python modules from sources onto a virtual environment 如何让pip将软件包安装到虚拟环境中? - How to get pip to install packages into the virtual environment? How to add local python files as a library to python virtual environment the same way as pip install to Airflow Docker - How to add local python files as a library to python virtual environment the same way as pip install to Airflow Docker Pip 在 Pip 虚拟环境中安装 SHAP 失败 - Pip Install SHAP Failed in Pip Virtual Environment 在 python 的虚拟环境中安装 pip 后无法导入 tensorflow - unable to import tensorflow after I pip install in a virtual environment in python 在虚拟环境中使用PIP,如何安装MySQL-python - Using PIP in a virtual environment, how do I install MySQL-python 使用 VS 代码 Python 扩展 - 如何将 python 模块安装到虚拟环境之外的永久位置? - Using VS Code Python extension - How to install python modules to a permanent location outside of a virtual environment? 如何创建仅包含一个版本的 python/pip 的 python 虚拟环境? - How can I create a python virtual environment that only includes one version of python/pip?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM