The user wants a Python CLI tool to manage virtual environments.
Key features needed for a useful venv manager:
Creation: Creating new environments with specific Python versions (if available) and names.
Listing: Showing existing environments managed by the tool.
Activation: Providing the command to activate (since a Python script cannot change the parent shell's state directly, it usually prints the command or tries to spawn a sub-shell, but printing is safer and more standard for a "helper" tool). Actually, a better approach for a "manager" is often storing them in a central directory so you don't have to be in the project folder.
Deletion: Removing environments.
Configuration: Where to store these environments? A central directory (like ~/.venvs or ~/.virtualenvs) is best practice (similar to virtualenvwrapper).
Technology Stack:
Language: Python 3.
Library: argparse for CLI argument parsing (standard lib), venv for creation (standard lib), os/pathlib/shutil for file operations.
Packaging: setuptools / pyproject.toml concept to make it installable.
Design Decisions:
Storage: Let's default to a folder in the user's home directory, e.g., ~/.pyvenv-manager.
Windows: <path>\Scripts\activate (This is tricky in Python CLI to execute directly in parent shell).
Constraint Check: A python script cannot change the parent shell's environment variables (like PATH). Therefore, the "activate" command should strictly output the command to run, or the tool should be a shell function wrapper.
Approach: To keep it simple Python-only, I will output the command the user needs to copy-paste, or explain that eval $(pymgr activate myenv) works if the tool prints the raw command.
Correction: Actually, the most user-friendly way is to have the python tool print the activation script path, and perhaps offer a shell hook. But for a basic CLI tool, just printing the command is the honest answer.
Better Approach: I'll add a shell script helper or instructions on how to alias it. But for the Python code itself, it will just print the instructions.
Refining the "Activate" feature:
Most tools like virtualenvwrapper require you to source a shell script.
For this specific request ("Develop a Python CLI tool"), I should provide the Python code. I will note the limitation of activation.
Let's write the code.
File Structure:
venv_manager/
__init__.py
cli.py (entry point)
setup.py (for installation)
Code Structure (cli.py):
Define VENV_DIR.
Function create_env(name, python_path)
Function list_envs()
Function remove_env(name)
Function activate_env(name) -> Prints the source ... command.
Adding "Go-To" functionality (Bonus):
Maybe cd into the directory? No, same restriction as activate.
Python Version Selection:
Allowing the user to specify a python path/version for creation is useful.
Reviewing the User Request: "Develop a Python CLI tool to manage virtual environments."
They likely want a complete, runnable example.
Deliverables:
The Python code (single file is easiest for copy-paste, but package structure is better for "developing"). I'll provide a single robust file that can be installed as a module.
Instructions on how to install and use it.
Explanation of the limitations (shell integration).
Specific Code Details:
Use pathlib.
Use argparse.
Use shutil.
Use sys.
Self-Correction during drafting: If I just print "Run this command", it's annoying.
Alternative: The tool could act as a wrapper. If you run pymgr run <name> python script.py, it executes inside the venv. That is very doable within Python.
I will add a run command. That solves the "using" the venv problem without needing shell hacks.
Final Plan:
Core: VenvManager class.
Commands:
create: venv -p logic.
ls: list folders.
rm: delete folder.
use: print activation command.
run: execute a command inside the venv (e.g., pymgr run myenv pip install requests).
Let's write the code.
Here is a complete, robust Python CLI tool to manage virtual environments. It uses the standard library argparse for the interface and venv for environment creation.
This tool stores all virtual environments in a central directory (e.g., ~/.virtualenvs) so you can manage them from anywhere without cluttering your project folders.
1. The Python Code
Save the following code into a file named venvcli.py.
python
2. How to Set It Up
To make this tool available globally as a command line utility (e.g., typing venvcli anywhere), follow these steps:
Option A: The Quick Way (Alias)
Save the file as venvcli.py in a folder (e.g., ~/scripts/).
Add an alias to your shell configuration file (.bashrc, .zshrc, or .bash_profile):
bash
alias venvcli='python3 /path/to/venvcli.py'
Restart your terminal or run source ~/.bashrc.
Option B: The Professional Way (pip install)
If you want to distribute this or install it cleanly, create a pyproject.toml file in the same folder as your script:
pyproject.toml
toml
[build-system]
requires = ["setuptools", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "venvcli"
version = "0.1.0"
description = "A virtual environment manager"
requires-python = ">=3.8"
[project.scripts]
venvcli = "venvcli:main"
Then install it locally:
bash
pip install -e .
Now you can simply type venvcli in your terminal.
3. How to Use It
Here are the commands available once the tool is running:
1. Create a new environment
bash
venvcli create my-project
# Or specifying a specific python version
venvcli create old-project --python /usr/bin/python2
2. List all environments
bash
venvcli list
3. Run commands inside an environment
This is a powerful feature that saves you from typing source activate. You can run pip or python scripts directly:
bash
venvcli run my-project -m pip install numpy pandas
venvcli run my-project my_script.py
4. Delete an environment
bash
venvcli remove my-project
4. Technical Details
Storage: It creates a hidden folder in your home directory (~/.venvcli_envs). This keeps your environments centralized rather than scattered across project folders.
Subprocess: It uses Python's subprocess module to call the standard venv module. This ensures compatibility across different Python versions.
Run Command: The run command constructs the absolute path to the python executable inside the specific virtual environment. This allows you to use the environment's packages without manually activating it first.
import argparse
import os
import sys
import subprocess
import shutil
from pathlib import Path
# Central location to store all virtual environments
# Uses the user's home directory to avoid permission issues
VENV_DIR = Path.home() / ".venvcli_envs"
class VenvManager:
def __init__(self, storage_path):
self.storage_path = storage_path
self.storage_path.mkdir(exist_ok=True)
def create(self, name, python_path=None):
"""Creates a new virtual environment."""
env_path = self.storage_path / name
if env_path.exists():
print(f"Error: Environment '{name}' already exists.")
return
print(f"Creating environment '{name}' at {env_path}...")
# Determine python executable
executable = python_path if python_path else sys.executable
try:
subprocess.run([executable, "-m", "venv", str(env_path)], check=True)
print(f"✅ Environment '{name}' created successfully.")
print(f"To activate it, run:\n\tsource {env_path}/bin/activate")
except subprocess.CalledProcessError as e:
print(f"Error creating environment: {e}")
def list(self):
"""Lists all managed environments."""
envs = [d for d in self.storage_path.iterdir() if d.is_dir()]
if not envs:
print("No environments found.")
return
print("Managed Virtual Environments:")
print("-" * 40)
for env in sorted(envs):
# Check for python executable to ensure it's a valid venv
if (env / "bin" / "python").exists():
print(f"📁 {env.name}")
def remove(self, name):
"""Removes an environment."""
env_path = self.storage_path / name
if not env_path.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(f"Removing '{name}'...")
shutil.rmtree(env_path)
print(f"✅ Environment '{name}' removed.")
else:
print("Aborted.")
def run(self, name, command):
"""Runs a command inside the virtual environment."""
env_path = self.storage_path / name
python_bin = env_path / "bin" / "python"
if not python_bin.exists():
print(f"Error: Environment '{name}' does not exist or is invalid.")
return
print(f"Running '{' '.join(command)}' in '{name}'...")
try:
subprocess.run([str(python_bin)] + command)
except KeyboardInterrupt:
print("\nExecution stopped.")
def main():
parser = argparse.ArgumentParser(description="A CLI tool to manage Python Virtual Environments.")
subparsers = parser.add_subparsers(dest="command", help="Available commands")
# Create command
parser_create = subparsers.add_parser("create", help="Create a new virtual environment")
parser_create.add_argument("name", help="Name of the environment")
parser_create.add_argument("--python", help="Path to python interpreter to use", default=None)
# List command
subparsers.add_parser("list", help="List all managed environments")
# Remove command
parser_remove = subparsers.add_parser("remove", help="Remove an environment")
parser_remove.add_argument("name", help="Name of the environment to remove")
# Run command
parser_run = subparsers.add_parser("run", help="Run a command inside an environment")
parser_run.add_argument("name", help="Name of the environment")
parser_run.add_argument("cmd", nargs="+", help="Command to run (e.g., pip install requests)")
args = parser.parse_args()
manager = VenvManager(VENV_DIR)
if args.command == "create":
manager.create(args.name, args.python)
elif args.command == "list":
manager.list()
elif args.command == "remove":
manager.remove(args.name)
elif args.command == "run":
manager.run(args.name, args.cmd)
else:
parser.print_help()
if __name__ == "__main__":
main()