How to Create a Mock Virtualenv with an Activation Script in Python

Create a mock virtualenv directory with a generated bash activation script using Python's standard library.

Easy Python 3.6+ Aug 9, 2026 Modern tooling 13 views 0 copies

Python code

31 lines
Python 3.6+
import os
import subprocess
import sys
from pathlib import Path


def mock_virtualenv(name: str = "myenv") -> Path:
    """Create a mock virtualenv directory and activation script."""
    env_dir = Path(name)
    env_dir.mkdir(exist_ok=True)
    (env_dir / "bin").mkdir(exist_ok=True)

    activate_script = f"""#!/bin/bash
# Mock activate script for {name}
export VIRTUAL_ENV="{env_dir.resolve()}"
export PATH="$VIRTUAL_ENV/bin:$PATH"
echo "Activated virtualenv: $VIRTUAL_ENV"
"""

    activate_path = env_dir / "bin" / "activate"
    activate_path.write_text(activate_script)
    activate_path.chmod(0o755)

    return env_dir


if __name__ == "__main__":
    venv_dir = mock_virtualenv()
    print(f"Mock venv created at: {venv_dir}")
    print(f"Activate with: source {venv_dir / 'bin' / 'activate'}")
    print(f"Activate script contents:\n{(venv_dir / 'bin' / 'activate').read_text()}")

Output

stdout
Mock venv created at: myenv
Activate with: source myenv/bin/activate
Activate script contents:
#!/bin/bash
# Mock activate script for myenv
export VIRTUAL_ENV="/absolute/path/to/myenv"
export PATH="$VIRTUAL_ENV/bin:$PATH"
echo "Activated virtualenv: $VIRTUAL_ENV"

How it works

The function creates a directory structure mimicking a real virtualenv, including a bin folder. It writes a bash script that sets VIRTUAL_ENV and PATH environment variables when sourced. The chmod(0o755) call makes the script executable. Using Path.write_text ensures the script is written to disk cleanly. This is useful for testing tools that inspect or interact with virtualenv structures without actually creating one.

Common mistakes

  • Forgetting to make the script executable with chmod when testing shell integration
  • Hardcoding paths instead of using `Path.resolve()` for portability
  • Not handling the script name for Windows environments with different activation patterns

Variations

  1. Use `tempfile.TemporaryDirectory()` to create the mock inside a temporary location for tests
  2. Generate a PowerShell activate script for Windows compatibility alongside the bash one

Real-world use cases

  • Testing CI/CD scripts that validate virtualenv activation without installing dependencies.
  • Generating lightweight sandbox environments for tutorial or documentation examples.
  • Validating that internal tooling detects and reports on virtualenv paths correctly.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Modern tooling

Related tutorials and quizzes for this topic.