Random Virtual Environment Creation with Python Version Selection

  • Share this:

Code introduction


This function creates a random virtual environment with a randomly chosen Python version and activates it. It first selects a random Python version, then creates a virtual environment using the venv library, and sets the Python version in the activate script by editing it.


Technology Stack : venv, os

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
import venv
import os

def create_random_venv(directory):
    """
    Create a random virtual environment with a random Python version and activate it.
    """
    # Generate a random Python version to use for the virtual environment
    python_version = random.choice(['3.6', '3.7', '3.8', '3.9', '3.10', '3.11'])
    
    # Create the virtual environment
    venv.create(directory, with_pip=True, python_version=python_version)
    
    # Activate the virtual environment
    activate_script = os.path.join(directory, 'Scripts', 'activate') if os.name == 'nt' else os.path.join(directory, 'bin', 'activate')
    with open(activate_script, 'w') as file:
        file.write(f"python={python_version}\n")
        file.write("deactivate\n")

# Example usage:
# create_random_venv('my_random_venv')                
              
Tags: