Creating a Random Python Virtual Environment with Venv

  • Share this:

Code introduction


This function uses the venv library to create a virtual environment and randomly install a Python package. It first defines a list of Python package names, then randomly selects one package, and uses the subprocess module to call pip to install it.


Technology Stack : venv, subprocess, os, random

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
import os
import sys
import subprocess

def create_virtual_env(env_name):
    # Create a virtual environment with random packages
    packages = ['numpy', 'pandas', 'matplotlib', 'requests', 'scikit-learn', 'tensorflow', 'opencv-python']
    random_package = random.choice(packages)
    try:
        subprocess.run([sys.executable, "-m", "venv", env_name], check=True)
        subprocess.run([os.path.join(env_name, 'bin', 'pip'), 'install', random_package], check=True)
        print(f"Virtual environment '{env_name}' created with package {random_package}.")
    except subprocess.CalledProcessError as e:
        print(f"Failed to create virtual environment: {e}")