The user wants a Python CLI tool for managing virtual environments, but the request is quite vague. I need to clarify aspects like OS and preferred libraries. I’m thinking of suggesting features like creating, listing, removing, activating, and installing dependencies. I could use the built-in venv module and a simple CLI setup with argparse. The simplest design might involve managing environments in a .venvs directory. I’ll deliver a single-file script, venvman.py, and explain that activating an environment in the current shell isn't feasible but can open a subshell.Designing CLI Tool Features
I need to create a main entry point for the tool and commands like init, create, list, remove, run, shell, and install. I want to consider safety with path operations and use only the standard library. I'm thinking “venvctl” sounds clear, but I might ask the user about their preference for libraries like click or argparse. Minimalist choice here leads me to select argparse. I’ll set the base directory for environments to default to /.venvs, allowing user overrides with an environment variable or CLI option.Creating the VenvManager Class
I’m outlining the data model for a class called VenvManager. It will include an initializer for the base directory and methods like env_path(), list_envs(), and create(). For create(), I'll determine the Python executable path using sys.executable if no specific version is provided. When removing an environment, I'll use shutil.rmtree. The run() method will execute commands in the virtual environment, constructing necessary environment variables. To start an interactive shell, I'll handle both POSIX and Windows cases by using the appropriate shell or command prompt.Constructing the Environment and CLI Commands
I’m setting up the environment for the virtual environment by copying os.environ. I'll assign the VIRTUAL_ENV variable based on the environment directory and adjust the PATH for POSIX and Windows accordingly. For the CLI commands, I’ll define them as follows: create with venvman.py create NAME [--python PYTHON_EXEC], list with venvman.py list, and remove with venvman.py remove NAME. Other commands will include info for showing location and Python version, plus shell to open a subshell, run to execute commands, and install as a simple wrapper for pip. I'll keep it focused on core functions without overcomplicating things, consolidating everything into one script, venvtool.py, along with documentation and usage instructions.Finalizing VenvManager Implementation
I’ll structure the main() function to use argparse. The script will support commands like create, list, remove, and shell, ensuring I handle edge cases properly, especially when commands are run or environments don't exist. I'll define VenvManager with methods for managing environments and running commands. Importantly, the environment will adjust based on the OS. I'll include usage examples, a minimal pyproject snippet for packaging, and a short description of limitations, ensuring everything is clear and concise without overwhelming details. Let's finalize the code carefully!Finalizing VenvTool CLI
I’m refining the _python_executable method to determine the correct executable path based on the OS. For the run() method, I’ll catch CalledProcessError for better error handling without cluttering the output. In main(), I’m structuring the argument parsing for commands like create, remove, and info, while allowing flexibility in input for install. I'll ensure both run and install correctly handle arguments passed to pip. Finally, I’ll add support for overriding the shell and provide a minimal packaging snippet for installation. Let’s wrap this up with a clear answer for the user! Below is a self‑contained Python CLI tool that manages virtual environments using only the standard library.
It supports:
A central directory for all envs (default: ~/.venvs or $VENVTOOL_HOME)
create – create a new venv
list – list all managed venvs
remove – delete an env
info – show location and Python version
shell – spawn an interactive shell inside an env
run – run any command inside an env
install – run pip install inside an env
1. The CLI tool (venvtool.py)
python
2. Basic usage
Assuming you saved it as venvtool.py and made it executable:
bash
chmod +x venvtool.py
Default env home is ~/.venvs (or $VENVTOOL_HOME if set).
Examples:
bash
# Create an env
./venvtool.py create myenv
# List envs
./venvtool.py list
# Show info
./venvtool.py info myenv
# Open a shell inside env
./venvtool.py shell myenv
# Run a command inside env
./venvtool.py run myenv python -m pip list
# Install packages (any pip args)
./venvtool.py install myenv requests==2.32.0 -r requirements.txt
# Remove env
./venvtool.py remove myenv
To use a different base directory:
bash
./venvtool.py --home ./venvs create proj1
./venvtool.py --home ./venvs list
3. Optional: install as a package / command
Minimal pyproject.toml if you want to install it via pip:
toml
[build-system]
requires = ["setuptools"]
build-backend = "setuptools.build_meta"
[project]
name = "venvtool"
version = "0.1.0"
description = "Simple CLI to manage Python virtual environments"
requires-python = ">=3.8"
[project.scripts]
venvtool = "venvtool:main"
Place venvtool.py next to pyproject.toml, then:
bash
pip install .
venvtool create myenv
If you want additional features (per-project envs, configuration files, or richer commands), tell me what workflow you have in mind and I can extend this tool accordingly.
#!/usr/bin/env python3
"""
venvtool: simple CLI to manage Python virtual environments.
Usage examples:
# Create an environment
venvtool.py create myenv
# List environments
venvtool.py list
# Spawn a shell inside an environment
venvtool.py shell myenv
# Run a command inside an environment
venvtool.py run myenv python -m pip list
# Install packages inside an environment
venvtool.py install myenv requests==2.32.0
# Remove an environment
venvtool.py remove myenv
"""
import argparse
import os
import shutil
import subprocess
import sys
from pathlib import Path
class VenvError(Exception):
"""Custom exception for virtual environment manager errors."""
class VenvManager:
def __init__(self, base_dir: Path):
self.base_dir = base_dir
def env_path(self, name: str) -> Path:
return self.base_dir / name
def list_envs(self):
if not self.base_dir.exists():
return []
return sorted(
p.name for p in self.base_dir.iterdir()
if p.is_dir()
)
def create(self, name: str, python: str | None = None):
env_dir = self.env_path(name)
if env_dir.exists():
raise VenvError(f"Environment '{name}' already exists at {env_dir}")
python_exe = python or sys.executable
cmd = [python_exe, "-m", "venv", str(env_dir)]
print(f"Creating environment '{name}' with {python_exe} at {env_dir}")
subprocess.run(cmd, check=True)
def remove(self, name: str):
env_dir = self.env_path(name)
if not env_dir.exists():
raise VenvError(f"Environment '{name}' does not exist")
print(f"Removing environment '{name}' at {env_dir}")
shutil.rmtree(env_dir)
def _ensure_exists(self, name: str) -> Path:
env_dir = self.env_path(name)
if not env_dir.exists():
raise VenvError(f"Environment '{name}' does not exist at {env_dir}")
return env_dir
@staticmethod
def _bin_dir(env_dir: Path) -> Path:
return env_dir / ("Scripts" if os.name == "nt" else "bin")
@staticmethod
def _python_executable(env_dir: Path) -> Path:
bin_dir = VenvManager._bin_dir(env_dir)
exe_name = "python.exe" if os.name == "nt" else "python"
return bin_dir / exe_name
def _env_for_process(self, env_dir: Path) -> dict:
env = os.environ.copy()
env["VIRTUAL_ENV"] = str(env_dir)
bin_dir = self._bin_dir(env_dir)
old_path = env.get("PATH", "")
env["PATH"] = str(bin_dir) + os.pathsep + old_path
return env
def info(self, name: str):
env_dir = self._ensure_exists(name)
py_exe = self._python_executable(env_dir)
version = "<unknown>"
try:
proc = subprocess.run(
[str(py_exe), "--version"],
check=False,
capture_output=True,
text=True,
)
version = (proc.stdout or proc.stderr).strip() or version
except Exception:
pass
print(f"Name: {name}")
print(f"Location: {env_dir}")
print(f"Python: {version}")
def shell(self, name: str):
env_dir = self._ensure_exists(name)
env = self._env_for_process(env_dir)
# Determine shell
if os.name == "nt":
shell = (
os.environ.get("VENVTOOL_SHELL")
or os.environ.get("COMSPEC")
or "cmd.exe"
)
else:
shell = (
os.environ.get("VENVTOOL_SHELL")
or os.environ.get("SHELL")
or "/bin/bash"
)
print(
f"Spawning shell '{shell}' in environment '{name}'. "
"Type 'exit' or Ctrl-D to leave."
)
subprocess.call([shell], env=env)
def run(self, name: str, cmd: list[str]):
if not cmd:
raise VenvError("No command specified to run")
env_dir = self._ensure_exists(name)
env = self._env_for_process(env_dir)
subprocess.run(cmd, env=env, check=True)
def install(self, name: str, pip_args: list[str]):
if not pip_args:
raise VenvError("No arguments supplied for 'pip install'")
env_dir = self._ensure_exists(name)
py_exe = self._python_executable(env_dir)
cmd = [str(py_exe), "-m", "pip", "install", *pip_args]
print(f"Running: {' '.join(cmd)}")
env = self._env_for_process(env_dir)
subprocess.run(cmd, env=env, check=True)
def build_parser() -> argparse.ArgumentParser:
default_home = os.environ.get("VENVTOOL_HOME", "~/.venvs")
parser = argparse.ArgumentParser(
prog="venvtool",
description="Manage Python virtual environments in a central directory.",
)
parser.add_argument(
"--home",
default=default_home,
help=(
"Directory to store virtual environments. "
f"Default: %(default)s"
),
)
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")
p_create.add_argument(
"-p",
"--python",
help="Python executable to use (default: current Python)",
)
# list
subparsers.add_parser(
"list",
help="List available virtual environments",
)
# remove
p_remove = subparsers.add_parser(
"remove",
help="Remove (delete) a virtual environment",
)
p_remove.add_argument("name", help="Name of the environment")
# info
p_info = subparsers.add_parser(
"info",
help="Show details about a virtual environment",
)
p_info.add_argument("name", help="Name of the environment")
# shell
p_shell = subparsers.add_parser(
"shell",
help="Spawn an interactive shell inside a virtual environment",
)
p_shell.add_argument("name", help="Name of the environment")
# run
p_run = subparsers.add_parser(
"run",
help="Run a command inside a virtual environment",
)
p_run.add_argument("name", help="Name of the environment")
p_run.add_argument(
"cmd",
nargs=argparse.REMAINDER,
help="Command to run inside the environment",
)
# install
p_install = subparsers.add_parser(
"install",
help="Run 'pip install' inside a virtual environment",
)
p_install.add_argument("name", help="Name of the environment")
p_install.add_argument(
"pip_args",
nargs=argparse.REMAINDER,
help="Arguments to pass to 'pip install' (e.g. requests==2.32.0 -r reqs.txt)",
)
return parser
def main(argv: list[str] | None = None) -> int:
parser = build_parser()
args = parser.parse_args(argv)
base_dir = Path(args.home).expanduser().resolve()
base_dir.mkdir(parents=True, exist_ok=True)
manager = VenvManager(base_dir)
try:
if args.command == "create":
manager.create(args.name, python=getattr(args, "python", None))
elif args.command == "list":
envs = manager.list_envs()
if not envs:
print(f"No environments found in {base_dir}")
else:
for name in envs:
print(name)
elif args.command == "remove":
manager.remove(args.name)
elif args.command == "info":
manager.info(args.name)
elif args.command == "shell":
manager.shell(args.name)
elif args.command == "run":
manager.run(args.name, args.cmd)
elif args.command == "install":
manager.install(args.name, args.pip_args)
else:
parser.error(f"Unknown command: {args.command}")
return 0
except VenvError as e:
print(f"Error: {e}", file=sys.stderr)
return 1
except subprocess.CalledProcessError as e:
# Propagate the exit code of the failing subprocess
print(f"Command failed with exit code {e.returncode}", file=sys.stderr)
return e.returncode
if __name__ == "__main__":
sys.exit(main())