Conceptualizing CLI Tool
I'm currently fleshing out the core functions for this CLI tool. It's becoming clearer how commands like "create," "list," "activate," and "delete" will operate. Thinking now about how to make the tool intuitive and user-friendly, I'm considering features like autocompletion and clear error messages.
Pinpointing Core Features
I'm now fully immersed in the core functionalities. Refining the operational model to include "create," "remove," "list," and "run" for venvs is key. I've opted for standard libraries for dependability, prioritizing robustness and ease of use. The choice of argparse, venv, os, and shutil makes this both simple and robust, avoiding external dependencies. The overall architecture is coalescing.
Considering Activation Strategies
I'm now grappling with the tricky challenge of shell activation within child processes. I'm exploring the implications for users and considering the need for shell-specific adaptations, possibly through aliases or functions. Centralized storage for virtual environments is another focus, considering a directory like ~/.py-venv-manager for ease of listing. I'm also planning for cross-platform compatibility, specifically addressing the differences in activation scripts between Windows and Unix systems.
Defining Activation Logic
I'm now zeroing in on activation strategies. The previous approach of direct manipulation of the shell environment within the Python script hit a dead end, so I'm now exploring how to best prompt users to activate the environment themselves. I'm focusing on the logic around generating and displaying commands that the user can copy/paste. The challenge now is to make sure this prompt is clear and correct for different shells and operating systems, which is the immediate focus.
Integrating the Run Command
I'm presently integrating the run command, focusing on its programmatic robustness. I'm leveraging subprocess.run to execute commands within the virtual environment. I'm also adding a command to output the virtual environment path, enabling manual sourcing by the user. I'm writing the structure with argparse to facilitate this process.
Defining Code Structure
I'm now structuring the code using a VenvManager class for organization. The key now is the shell integration, specifically providing a snippet for the user to add as a shell function or alias, which will truly enable the 'activate' functionality. This adds essential value, as it makes using the virtual environments simple and seamless. I'm focusing on the final polish, with subprocess.run being correctly implemented.
Completing Usage Documentation
I'm presently building the usage guide, clearly explaining installation and command usage. The guide will have examples for a user to see the commands in action. The tool's structure is solidified: It creates, lists, deletes, runs, and can activate a venv, with OS independence through pathlib. I believe it's ready for general use.
This is a complete, zero-dependency Python CLI tool to manage virtual environments.
It uses the Standard Library only (argparse, venv, subprocess, etc.), so you don't need to install anything to run the tool itself.
Features
- Centralized: Stores all environments in
~/.py-venvs/.
- Create: Easily build new environments.
- Run: Execute commands inside a specific environment without activating it first.
- Delete: Remove old environments.
- Cross-Platform: Works on Windows and Linux/macOS.
The Python Script (vman.py)
Save this code into a file named vman.py.
#!/usr/bin/env python3
import argparse
import venv
import os
import sys
import shutil
import subprocess
import platform
from pathlib import Path
# Configuration: Where venvs are stored
HOME_DIR = Path.home()
VENVS_DIR = HOME_DIR / ".py-venvs"
class VenvManager:
def __init__(self, base_dir: Path):
self.base_dir = base_dir
self.base_dir.mkdir(exist_ok=True)
self.is_windows = platform.system().lower() == "windows"
def _get_venv_path(self, name: str) -> Path:
return self.base_dir / name
def _get_python_executable(self, name: str) -> Path:
"""Returns path to python executable inside venv based on OS."""
env_path = self._get_venv_path(name)
if self.is_windows:
return env_path / "Scripts" / "python.exe"
else:
return env_path / "bin" / "python"
def create(self, name: str):
target = self._get_venv_path(name)
if target.exists():
print(f"❌ Error: Environment '{name}' already exists.")
return
print(f"🔨 Creating virtual environment: {name}...")
try:
venv.create(target, with_pip=True)
print(f"✅ Successfully created '{name}'")
print(f" Path: {target}")
except Exception as e:
print(f"❌ Failed to create environment: {e}")
def list_envs(self):
print(f"📂 Managed Environments in {self.base_dir}:")
items = [i for i in self.base_dir.iterdir() if i.is_dir()]
if not items:
print(" (No environments found)")
return
for item in items:
print(f" • {item.name}")
def remove(self, name: str):
target = self._get_venv_path(name)
if not target.exists():
print(f"❌ Error: Environment '{name}' not found.")
return
confirm = input(f"⚠️ Are you sure you want to delete '{name}'? [y/N]: ")
if confirm.lower() != 'y':
print("Operation cancelled.")
return
try:
shutil.rmtree(target)
print(f"🗑️ Deleted '{name}'")
except Exception as e:
print(f"❌ Error deleting directory: {e}")
def get_activation_path(self, name: str):
"""Prints the shell command to activate the environment."""
target = self._get_venv_path(name)
if not target.exists():
print(f"❌ Environment '{name}' not found.")
sys.exit(1)
if self.is_windows:
script = target / "Scripts" / "activate.bat"
print(f"{script}")
else:
script = target / "bin" / "activate"
print(f"source {script}")
def run_command(self, name: str, command: list):
"""Runs a command using the venv's python interpreter."""
target = self._get_venv_path(name)
if not target.exists():
print(f"❌ Environment '{name}' not found.")
return
exe = self._get_python_executable(name)
if not exe.exists():
print(f"❌ Python executable not found at {exe}. Is the venv corrupt?")
return
# If the user types "pip install x", we run "path/to/python -m pip install x"
# If the user types "python script.py", we run "path/to/python script.py"
cmd_to_run = []
# If the first arg is pip or python, we adjust slighty for safety
if command[0] == 'python':
cmd_to_run = [str(exe)] + command[1:]
elif command[0] == 'pip':
cmd_to_run = [str(exe), '-m', 'pip'] + command[1:]
else:
# Just try to run the executable from within the bin folder context
# This is tricky, so usually sticking to python/pip invoke is safer.
# Here we just set the path env variable and run normally
env_vars = os.environ.copy()
bin_dir = exe.parent
env_vars["PATH"] = str(bin_dir) + os.pathsep + env_vars["PATH"]
cmd_to_run = command
print(f"🚀 Running in '{name}': {' '.join(cmd_to_run)}")
try:
subprocess.run(cmd_to_run, check=True)
except subprocess.CalledProcessError as e:
print(f"❌ Command failed with error code {e.returncode}")
except FileNotFoundError:
print(f"❌ Command not found: {command[0]}")
def main():
parser = argparse.ArgumentParser(description="Simple Python Virtual Env Manager")
subparsers = parser.add_subparsers(dest="command", required=True)
# Create
p_create = subparsers.add_parser("create", help="Create a new virtual environment")
p_create.add_argument("name", help="Name of the environment")
# List
subparsers.add_parser("list", help="List all environments")
# Remove
p_remove = subparsers.add_parser("delete", help="Delete a virtual environment")
p_remove.add_argument("name", help="Name of the environment")
# Activate Info
p_path = subparsers.add_parser("path", help="Get activation path")
p_path.add_argument("name", help="Name of the environment")
# Run
p_run = subparsers.add_parser("run", help="Run a command inside an environment")
p_run.add_argument("name", help="Name of the environment")
p_run.add_argument("cmd", nargs=argparse.REMAINDER, help="Command to run (e.g. pip install requests)")
args = parser.parse_args()
manager = VenvManager(VENVS_DIR)
if args.command == "create":
manager.create(args.name)
elif args.command == "list":
manager.list_envs()
elif args.command == "delete":
manager.remove(args.name)
elif args.command == "path":
manager.get_activation_path(args.name)
elif args.command == "run":
if not args.cmd:
print("❌ Please provide a command to run.")
else:
manager.run_command(args.name, args.cmd)
if __name__ == "__main__":
main()
Installation
- Make the script executable (Linux/Mac):
chmod +x vman.py
- Ideally, add it to your PATH or alias it in your
.bashrc / .zshrc:
alias vman="python3 /path/to/vman.py"
Usage Guide
1. Create a new environment
Creates a fresh environment in the central directory (~/.py-venvs/myproject).
vman create myproject
2. List environments
vman list
# Output:
# 📂 Managed Environments...
# • myproject
# • data-analysis
3. Install packages (Run command)
You don't need to activate the shell to install libraries. You can run pip directly inside the env:
vman run myproject pip install requests pandas
4. Run a Python script
Runs main.py using the python interpreter belonging to myproject:
vman run myproject python main.py
5. Delete an environment
vman delete myproject
💡 Advanced: How to "Switch" Shells
A Python script cannot directly change your current shell environment (it runs in a child process). To support a command like vman activate myproject, you need a Shell Function wrapper.
Add this to your .bashrc or .zshrc:
vman() {
if [ "$1" = "activate" ]; then
# Ask python for the path, then evaluate it in the current shell
CMD=$(python3 /path/to/vman.py path "$2")
if [ $? -eq 0 ]; then
eval "$CMD"
else
echo "Error locating environment"
fi
else
# Pass everything else to the python script
python3 /path/to/vman.py "$@"
fi
}
Now you can do:
vman activate myproject
And your terminal prompt will change (e.g., (myproject) user@host $).