Random Virtual Environment Creation with venv

  • Share this:

Code introduction


This function uses the venv library to create a virtual environment with a random name. The user can specify the directory where the virtual environment will be stored.


Technology Stack : venv

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
import venv

def create_random_venv(directory):
    """
    Create a random virtual environment using the venv module.

    Args:
        directory (str): The directory where the virtual environment will be created.
    """
    # Generate a random directory name for the virtual environment
    random_dir = f"venv_{random.randint(1000, 9999)}"
    full_path = f"{directory}/{random_dir}"

    # Create the virtual environment
    venv.create(full_path, with_pip=True)

    print(f"Virtual environment created at {full_path}")                
              
Tags: