- Advanced Python Programs
- Advanced Python Programs - Home
Python Basics
- Introduction and Setup
- Create a system info collector CLI using platform, sys, and psutil.
- Build a virtual environment manager using venv and subprocess.
- Script to generate a project folder with auto README, .gitignore, and starter script.
- Python version compatibility checker for scripts (uses ast, tokenize).
- Auto-install missing modules when ImportError is detected.
- Create a startup script that logs Python path, version, and user info.
- Build a tool to compare two Python environments (pip freeze diff).
- Script to automate code linting, formatting (using black, flake8, isort).
- Develop a python --info clone that shows detailed interpreter config.
- Set up and test a pyproject.toml file for a sample module.
- Package a module and publish it to TestPyPI.
- Script to check environment memory usage while loading modules.
- Write a Python script that upgrades all installed packages safely.
- Program to back up and restore .py and .ipynb files in a directory.
- Use argparse to build a multi-command CLI utility tool.
- Compare CPython vs PyPy performance on a benchmark task.
- Automate logging and error capturing for all first-time scripts.
- Build a script to run code snippets interactively with audit logging.
- Create a "Getting Started Wizard" for first-time learners.
- Write a Python sandbox that runs code with restricted permissions.
- Variables and Data Types
- Implement dynamic type conversion using regex rules on string inputs.
- Auto-detect and correct mistyped literals (e.g., "5.0O" → "500").
- Create a type-tracer that logs type transitions across operations.
- Build a system to simulate memory-efficient representations (bitfields).
- Write a program that deep-checks nested data structure types.
- Simulate real-time data stream type validation using decorators.
- Create a tool that visualizes Python object memory layout.
- Build a mini schema validator for data (like JSON schema).
- Explore data coercion rules (like float+int, str*int) with examples.
- Type-safe expression evaluator (add type checks to an eval function).
- Program to convert mixed-type lists to homogeneous types.
- Create custom class TypeEnforcer to reject illegal type assignments.
- Dynamic variable inspector CLI using locals() and globals().
- Use mypy and typing to enforce type hints and generate reports.
- Build a program that tracks how often each data type is used.
- Create a symbolic type system to simulate type inference.
- Program to clean and standardize inconsistent data types in a CSV.
- Visualize type distributions in a dataset using a pie chart.
- Parse and evaluate expressions based on runtime-detected types.
- Use metaclasses to auto-type-check class properties.
- Operators
- Create a visual operator precedence tester with expressions.
- Implement a full infix → postfix → result evaluator using stack.
- Write a symbolic math engine using operator overloading.
- Build a spreadsheet-style formula evaluator supporting cells.
- Implement a binary expression tree from math strings.
- Create a vector class that supports all mathematical operators.
- Overload operators to simulate a Matrix class (with +, *, etc.).
- Build a simulator for circuit logic (AND, OR, NOT using bitwise ops).
- Create a filter expression parser (e.g., "age>30 and score<=80").
- Build a secure math expression evaluator (no eval()).
- Compare expression results across float/int/bool for precision.
- Implement a mini-language interpreter using custom operators.
- Develop a program to visualize operator evaluation order.
- Create a complex number calculator using class and operator overloading.
- Simulate a search engine filter logic using boolean operators.
- Build a finance calculator for tax slabs (tiered with conditions).
- Use bitwise operators to encode/decode permissions (Unix-style).
- Test short-circuit evaluation with custom objects and logs.
- Build a CLI tool that runs operator tests on user input.
- Create a GUI-based calculator supporting all operator types.
- Input and Output (Advanced)
- Build a CLI form handler that saves data in JSON/XML/CSV.
- Real-time data logger from user input to rotating file logs.
- Input validator that uses regex, length, type, and range checks.
- Password input tool with masking and strength meter.
- Create a reusable interactive menu system.
- Build a resume-builder CLI that outputs to Markdown and PDF.
- Implement a chatbot-like input collector with context.
- Save formatted user input into Excel using openpyxl.
- Use input() to take dynamic Python code and safely evaluate.
- Read and parse structured data input (YAML, XML).
- Create a console wizard that guides users through data entry.
- CLI survey that outputs charts of responses using matplotlib.
- Create a tool to validate and clean bulk data from user entries.
- Prompt user for input and send it via POST request to an API.
- Record input sessions and save as log with timestamps.
- Create a pseudo form validator with input loop + correction.
- Build a terminal app that accepts file paths and processes them.
- Develop a custom input prompt framework with templates.
- Validate and enrich contact details entered by the user (name/email).
- Build a script that generates a config file based on user inputs.
Module 2: Control Structures
- Conditional Statements
- Custom Grading System – Assign letter grades with optional GPA scale.
- Tax Calculator – Slab-based income tax with deductions and surcharges.
- Loan Eligibility Checker – Based on salary, credit score, age.
- Nested Condition Analyzer – Debug tool to visualize if-elif-else flow.
- Advanced BMI Categorizer – Classify health risk using BMI + age + gender.
- Eligibility Checker for Competitive Exams – Uses multiple nested conditions.
- Age-based Access Control System – Assign privileges by age groups.
- Custom Rule Engine – Accepts user-defined conditions and evaluates.
- Dynamic If-Else Generator – Take user conditions and generate Python code.
- Compare 3 or More Objects (Scores, Distances) – With tie-break logic.
- Medical Diagnosis Rule Checker – Use conditions to suggest possible symptoms.
- Electricity Bill Estimator – Different rates for tiers of usage.
- Scholarship Eligibility Calculator – Uses multi-param criteria.
- Compare Dates or Time Intervals – Determine recency, time left, etc.
- Smart Calculator with Conditional Error Checks – e.g., divide-by-zero, invalid op.
- Credit Card Approval Simulator – Based on income, age, history.
- Multi-Language Greeting System – Based on input locale.
- Dynamic Pricing Model – Based on season, demand, location.
- Insurance Premium Estimator – Based on driver’s profile.
- Hotel Room Assignment Logic – Based on group size and preferences.
- Looping Statements - (for, while)
- Pattern Generator Engine – Choose shape, size, and symbol.
- Sudoku Grid Validator – Iterate through rows, cols, and subgrids.
- Prime Number Counter with Stats – Count, sum, mean of all primes in range.
- Progress Bar Animation in Terminal – Simulated loading loop.
- Calendar Renderer – Print calendar view using nested loops.
- Reverse Multiplication Table Generator – From N to 1 in rows.
- Factorial Table Generator – Show factorials of first N numbers.
- User Login System with Retry Limit – Allow 3 attempts.
- Simulate Bank ATM Menu – Loop with transaction types.
- Loop-Based Art Generator (ASCII) – Complex figures using logic.
- Iterate Over Nested JSON – Parse and print key-value tree.
- Custom Loop Breaker – Use input to break or continue dynamically.
- Dynamic Loop Builder from Text Input – Convert plain rules to loops.
- Pyramid Pattern with Alphabets or Numbers – Custom alignment.
- User Polling System – Loop to take repeated survey inputs.
- Fibonacci Sequence Analyzer – Find nth term, sum, average.
- Interactive Flashcards in a Loop – Present until mastery.
- Simulation: Car Fuel Consumption Until Empty – Break loop at 0.
- Calculate Compound Interest Year by Year – Show yearly breakdown.
- Time Tracker: Display Clock Every 1 Sec – Stop after N seconds.
- Loop Control Statements (break, continue, pass)
- Password Validator with Break on Success – Retry until valid input.
- Loop Skipping Specific Conditions – e.g., skip weekends in date loop.
- Data Cleaning with Continue – Skip invalid rows in list of dicts.
- Game Menu Loop with Break to Exit – Continue looping until “exit”.
- Log Scanner: Stop at First Error Entry – Demonstrate break.
- Prime Finder with Pass Placeholder for Future Optimizations.
- Custom Retry Mechanism with Break and Counter.
- Loop Through Sensor Data – Continue if Reading < Threshold.
- Shopping Cart Simulator – Exit loop when budget exhausted.
- Pass as Empty Handler in Function Loops.
- Email List Parser – Skip Invalid Emails using Continue.
- For-Else Loop Example – Search for Item, Confirm if Not Found.
- Simulate Elevator Stops – Skip Out-of-Order Floors.
- Simulate Turn-Based Game – Use Continue for Skipped Turn.
- Log Parser with Multiple Exit Conditions.
- Interactive Quiz – Break After 3 Wrong Answers.
- Random Number Generator – Pass if Even, Stop on Divisible by 7.
- Skip Comments While Reading a File.
- Fast Search in Dataset – Break on First Match, Pass on Errors.
- Infinite Menu Loop with Controlled Break.
Module 3: Functions and Recursion
- Defining and Calling Functions
- Function to Auto-Format Report Cards – Accepts data and prints styled output.
- Keyword-Only Argument Enforcer – Prevents positional usage.
- Function to Summarize Dataset – Mean, median, mode, range with *args.
- Create a Function Registry – Dynamically register callable functions.
- Function that Returns Multiple Statistical Results – e.g., mean, std, var.
- Decorator-Free Memoization with Function Wrapping.
- Factory Function That Returns Specialized Functions.
- Function Call Logger with Timestamps (using datetime).
- Function that Accepts Another Function and Logs Its Output.
- Multiple Argument Handling with Type Enforcement.
- Build a Secure Eval Function That Limits Scope.
- Dynamic Function Calling from a String (using globals()).
- Function to Perform Chained Transformations on Text.
- Higher-Order Function: Accepts Sorting Rule as Function.
- Create a Timer Wrapper for Any Callable.
- Function to Recursively Flatten Nested Lists.
- Function that Builds Markdown Tables from Nested Lists.
- Function to Convert Dictionary to Query String.
- Function with Dynamic Default Value Generator.
- Function Comparison Tool (compares logic by AST).
- Arguments and Parameters
- Function to Accept Unlimited Named Arguments and Return JSON.
- Create a Flexible Currency Converter Using **kwargs.
- Dynamic Calculator Function Using *args.
- Logger Function That Accepts Log Type and Metadata as kwargs.
- Function That Accepts Rules and Applies to List (like filter).
- Build Function Dispatcher with Argument Inspection.
- Convert Flat Args into Nested Dictionary Structure.
- Type Annotated Function With Runtime Type Checking.
- Argument Handler for CLI Tools Using argparse.
- Simulate API Call Signature with Optional/Required Parameters.
- Build Template Renderer Using Named Placeholders.
- Create Default Parameter Based on Other Inputs.
- Use inspect to Analyze Function Parameters.
- Function that Accepts Inputs from YAML File and Executes Task.
- Dynamic Field Validator Function With Rules Passed as kwargs.
- Named Parameter Resolver With Defaults and Fallbacks.
- Function With Error Reporting for Each Argument.
- Parameter Flattening Utility Function.
- Function Overloader That Chooses by Argument Count.
- Smart Validator With Switchable Rules via kwargs.
- Lambda, map, filter, reduce
- Use map to Clean, Normalize, and Standardize CSV Data.
- Use filter to Remove Incomplete or Corrupt Records.
- Use reduce to Perform Cumulative Summation of Dataset.
- Use Lambda for Dynamic Sorting Rules (length, frequency, etc.).
- Lambda for Generating Fibonacci Sequence in List Comprehension.
- Custom Lambda-Based Encryption for Strings.
- Pipeline System Using map → filter → reduce on JSON Records.
- Lambda to Validate Form Fields Based on Type Rules.
- Chained Lambdas for Text Cleanup: Lowercase → Strip → Replace.
- Use map to Apply Markdown Formatting to a List of Strings.
- Use reduce to Calculate GCD/LCM of List of Integers.
- Use filter to Extract Users Over Age X with Score > Y.
- Lambda to Simulate Expression Evaluator (a op b).
- Create a Decorator That Replaces Function With a Lambda Dynamically.
- Create Nested Lambda for Polynomial Functions.
- Sort List of Dicts Using Lambda Keys with Fallbacks.
- Use map to Reformat Date Strings in Data.
- Build a Text Summarizer Using Lambda to Reduce Sentences.
- Lambda-Based Unit Converter Factory.
- Function to Create Lambda Chains Dynamically from Configs.
- Recursion
- Recursive Directory Scanner – Walks file system like os.walk().
- Recursive Tree Printer – For nested dictionaries or JSON structures.
- Recursively Flatten Any Nested List/Dict Structure.
- Solve Tower of Hanoi Problem and Print Steps.
- Find All Subsets (Power Set) of a Given List.
- Generate All Permutations of a String Recursively.
- Recursively Reverse a Linked List (or simulate with list).
- Solve a Maze Path Using Recursion and Backtracking.
- Binary Search Implementation (Recursive).
- Parse Nested Mathematical Expression (e.g., "3(2+1)").*
- Recursive Fibonacci with Memoization.
- Sudoku Solver Using Recursive Backtracking.
- Recursively Evaluate a JSON Rule Engine.
- Generate Pascal’s Triangle Recursively.
- Simulate File Copying with Nested Folders Recursively.
- Count Leaf Nodes in a Tree Represented with Nested Lists.
- Solve N-Queens Problem Using Recursion.
- Recursive Web Crawler (Limit by Depth).
- Expression Tree Evaluation Recursively.
- Recursive Palindrome Checker with Substring Reduction.
Advanced Python Programs
![]() Share with a Friend |
Introduction and Setup
Build a Virtual Environment Manager using venv and subprocess - Advanced Python Program
Prereqs: Python 3.10+,
pip install psutil black flake8 isort twine build rich
(some scripts also use colorama or tomllib on <3.11).
Virtual Environment Manager
File Name : venvman.py
Description: Create/list/remove virtual environments in a configurable folder.
Usage:
python venvman.py create myenv
python venvman.py list
python venvman.py remove myenv
#!/usr/bin/env python3 import argparse, os, shutil, subprocess, sys from pathlib import Path ROOT = Path.home() / ".venvs" ROOT.mkdir(exist_ok=True) if __name__ == "__main__": ap = argparse.ArgumentParser() sub = ap.add_subparsers(dest="cmd", required=True) p_create = sub.add_parser("create"); p_create.add_argument("name") p_rm = sub.add_parser("remove"); p_rm.add_argument("name") sub.add_parser("list") args = ap.parse_args() if args.cmd == "create": target = ROOT / args.name if target.exists(): print("Already exists", file=sys.stderr); sys.exit(1) subprocess.check_call([sys.executable, "-m", "venv", str(target)]) print("Created:", target) print("Activate:") if os.name == "nt": print(fr"{target}\\Scripts\\activate") else: print(fr"source {target}/bin/activate") elif args.cmd == "list": for p in sorted(ROOT.iterdir()): if (p / ("Scripts" if os.name=="nt" else "bin") / "python").exists(): print(p.name) elif args.cmd == "remove": target = ROOT / args.name shutil.rmtree(target, ignore_errors=True) print("Removed:", target)
Output
OUTPUT 1 :D:\py_prog>python venvman.py create myenv
Created: C:\Users\.venvs\myenv
Activate:
C:\Users\.venvs\myenv\\Scripts\\activate
D:\py_prog>python venvman.py list
D:\py_prog>python venvman.py remove myenv
Removed: C:\Users\.venvs\myenv
Virtual Environment Manager - Step by Step Explanation
File Name : venvman.py
Description: Create/list/remove virtual environments in a configurable folder.
Usage:
python venvman.py create myenv
python venvman.py list
python venvman.py remove myenv
#!/usr/bin/env python3 """ venvman.py - Minimal virtual environment manager (cross-platform) Commands: create[--python /path/to/python] Create a new venv under $VENV_HOME or ~/.venvs list List all venvs remove Delete a venv info Show interpreter/build/site-packages path Print the venv path run -- Run a command inside the venv pip Run pip inside the venv (install/uninstall/show/…) freeze Show pip freeze for that venv export -o requirements.txt Save pip freeze to a file import -r requirements.txt Install from a requirements file Environment: VENV_HOME Root directory for environments (default: ~/.venvs) """ from __future__ import annotations import argparse import os import shutil import subprocess import sys from pathlib import Path from typing import List # ---------- Config & cross-platform constants ---------- ROOT = Path(os.environ.get("VENV_HOME", Path.home() / ".venvs")) BIN_DIR = "Scripts" if os.name == "nt" else "bin" PY_NAME = "python.exe" if os.name == "nt" else "python" PIP_NAME = "pip.exe" if os.name == "nt" else "pip" # ---------- Helpers ---------- def venv_path(name: str) -> Path: return ROOT / name def venv_python(name: str) -> Path: return venv_path(name) / BIN_DIR / PY_NAME def venv_pip(name: str) -> Path: return venv_path(name) / BIN_DIR / PIP_NAME def ensure_exists(name: str) -> None: if not venv_python(name).exists(): sys.exit(f"[!] Environment '{name}' not found at {venv_path(name)}") def check_call(cmd: List[str], **kwargs) -> None: subprocess.check_call(cmd, **kwargs) # ---------- Commands ---------- def cmd_create(args: argparse.Namespace) -> None: ROOT.mkdir(parents=True, exist_ok=True) target = venv_path(args.name) if target.exists(): sys.exit(f"[!] Already exists: {target}") py = args.python or sys.executable print(f"[*] Creating venv '{args.name}' with {py} ...") check_call([py, "-m", "venv", str(target)]) print(f"[+] Created: {target}") print("[i] Activate manually:") if os.name == "nt": print(fr" {target}\Scripts\activate") else: print(f" source {target}/bin/activate") def cmd_list(_args: argparse.Namespace) -> None: if not ROOT.exists(): print("(no environments)") return rows = [] for p in sorted(ROOT.iterdir()): interp = p / BIN_DIR / PY_NAME if interp.exists(): rows.append((p.name, interp)) if not rows: print("(no environments)") return width = max(len(n) for n, _ in rows) for name, interp in rows: print(f"{name:<{width}} -> {interp}") def cmd_remove(args: argparse.Namespace) -> None: path = venv_path(args.name) if not path.exists(): print(f"[i] Not found: {path}") return print(f"[*] Removing {path} ...") shutil.rmtree(path) print("[+] Removed.") def cmd_info(args: argparse.Namespace) -> None: ensure_exists(args.name) py = str(venv_python(args.name)) # Ask the venv's python to describe itself in JSON (robust across platforms) out = subprocess.check_output( [ py, "-c", ( "import sys,sysconfig,platform,site,json;" "print(json.dumps({" "'version':sys.version.replace('\\n',' ')," "'implementation':platform.python_implementation()," "'executable':sys.executable," "'prefix':sys.prefix," "'platform':sys.platform," "'paths':sysconfig.get_paths()," "'site':site.getsitepackages() if hasattr(site,'getsitepackages') else []" "}))" ), ], text=True, ) import json info = json.loads(out) print(f"Name: {args.name}") print(f"Path: {venv_path(args.name)}") print(f"Executable: {info['executable']}") print(f"Impl/Ver: {info['implementation']} {info['version']}") print(f"Platform: {info['platform']}") print("Paths:") for k, v in info["paths"].items(): print(f" {k:<12} {v}") if info["site"]: print("Site-packages:") for sp in info["site"]: print(f" - {sp}") def cmd_path(args: argparse.Namespace) -> None: ensure_exists(args.name) print(venv_path(args.name)) def cmd_run(args: argparse.Namespace) -> None: ensure_exists(args.name) if not args.cmd: sys.exit("[!] Provide a command after --, e.g. venvman run myenv -- python -V") env = os.environ.copy() env["PATH"] = str(venv_path(args.name) / BIN_DIR) + os.pathsep + env.get("PATH", "") env["VIRTUAL_ENV"] = str(venv_path(args.name)) # On Windows, prefer the venv's Python if user asked to run "python" rc = subprocess.call(args.cmd, env=env) sys.exit(rc) def cmd_pip(args: argparse.Namespace) -> None: ensure_exists(args.name) if not args.pip_args: sys.exit("[!] Provide pip arguments, e.g. venvman pip myenv install requests") check_call([str(venv_pip(args.name)), *args.pip_args]) def cmd_freeze(args: argparse.Namespace) -> None: ensure_exists(args.name) check_call([str(venv_pip(args.name)), "freeze"]) def cmd_export(args: argparse.Namespace) -> None: ensure_exists(args.name) out = subprocess.check_output([str(venv_pip(args.name)), "freeze"], text=True) Path(args.output).write_text(out, encoding="utf-8") print(f"[+] Wrote {args.output}") def cmd_import(args: argparse.Namespace) -> None: ensure_exists(args.name) req = Path(args.requirements) if not req.exists(): sys.exit(f"[!] Requirements not found: {req}") check_call([str(venv_pip(args.name)), "install", "-r", str(req)]) # ---------- CLI wiring ---------- def build_parser() -> argparse.ArgumentParser: ap = argparse.ArgumentParser( prog="venvman", description="Manage Python virtual environments using venv" ) sub = ap.add_subparsers(dest="cmd", required=True) p = sub.add_parser("create", help="Create a new virtual environment") p.add_argument("name") p.add_argument("--python", help="Python interpreter to use (defaults to current)") p.set_defaults(func=cmd_create) p = sub.add_parser("list", help="List all environments") p.set_defaults(func=cmd_list) p = sub.add_parser("remove", help="Remove an environment") p.add_argument("name") p.set_defaults(func=cmd_remove) p = sub.add_parser("info", help="Show environment details") p.add_argument("name") p.set_defaults(func=cmd_info) p = sub.add_parser("path", help="Print the environment path") p.add_argument("name") p.set_defaults(func=cmd_path) p = sub.add_parser("run", help="Run a command inside the environment") p.add_argument("name") p.add_argument( "cmd", nargs=argparse.REMAINDER, help="Command to run (prefix with -- to separate)", ) p.set_defaults(func=cmd_run) p = sub.add_parser("pip", help="Run pip inside the environment") p.add_argument("name") p.add_argument("pip_args", nargs=argparse.REMAINDER) p.set_defaults(func=cmd_pip) p = sub.add_parser("freeze", help="pip freeze inside the environment") p.add_argument("name") p.set_defaults(func=cmd_freeze) p = sub.add_parser("export", help="Export requirements to a file") p.add_argument("name") p.add_argument("-o", "--output", required=True) p.set_defaults(func=cmd_export) p = sub.add_parser("import", help="Install from a requirements file") p.add_argument("name") p.add_argument("-r", "--requirements", required=True) p.set_defaults(func=cmd_import) return ap def main(argv: List[str] | None = None) -> None: parser = build_parser() args = parser.parse_args(argv) args.func(args) if __name__ == "__main__": main()
Example usage & outputs (abridged)
Output
OUTPUT 1 :
# 1) Create an environment
$ python venvman.py create demo
[*] Creating venv 'demo' with /usr/bin/python3 ...
[+] Created: /home/user/.venvs/demo
[i] Activate manually:
source /home/user/.venvs/demo/bin/activate
# 2) List environments
$ python venvman.py list
demo -> /home/user/.venvs/demo/bin/python
# 3) Show detailed info
$ python venvman.py info demo
Name: demo
Path: /home/user/.venvs/demo
Executable: /home/user/.venvs/demo/bin/python
Impl/Ver: CPython 3.11.9 (main, ...)
Platform: linux
Paths:
data /home/user/.venvs/demo
include /home/user/.venvs/demo/include
platlib /home/user/.venvs/demo/lib/python3.11/site-packages
purelib /home/user/.venvs/demo/lib/python3.11/site-packages
...
Site-packages:
- /home/user/.venvs/demo/lib/python3.11/site-packages
# 4) Install packages inside that venv (pip passthrough)
$ python venvman.py pip demo install requests
Collecting requests ...
Successfully installed requests-2.32.3 ...
# 5) Run any command inside the venv (PATH is adjusted)
$ python venvman.py run demo -- python -V
Python 3.11.9
# 6) Freeze & export requirements
$ python venvman.py freeze demo
requests==2.32.3
$ python venvman.py export demo -o requirements.txt
[+] Wrote requirements.txt
# 7) Import requirements
$ python venvman.py import demo -r requirements.txt
Processing ./requirements.txt
Requirement already satisfied: requests==2.32.3 ...
# 8) Remove the env
$ python venvman.py remove demo
[*] Removing /home/user/.venvs/demo ...
[+] Removed.
What this tool does (detailed description)
- Creates isolated virtual environments with python -m venv, defaulting to a tidy root ($VENV_HOME or ~/.venvs).
- Lists environments by scanning that root and confirming a valid interpreter exists.
- Removes environments safely by deleting the directory tree.
- Shows info by asking the venv’s own Python to report version, implementation, config paths, and site-packages (this avoids guessing).
- Runs commands inside the environment by prepending the venv’s bin/Scripts to PATH and exporting VIRTUAL_ENV.
- Delegates to pip inside the venv for installs, upgrades, and queries.
- Exports a deterministic requirements.txt via pip freeze, and imports it later.
Step-by-step explanation
- Config & constants
- Detect a root folder for venvs (ROOT): $VENV_HOME or ~/.venvs.
- Pick correct subfolder/executable names on Windows vs Unix (BIN_DIR, PY_NAME, PIP_NAME).
- Helper functions
- venv_path(name) → where the env lives.
- venv_python(name) / venv_pip(name) → paths to the venv’s Python/Pip.
- ensure_exists(name) → exits early with a clear message if missing.
- create
- Ensures ROOT exists; bails if the target already exists.
- Calls [python, -m, venv, <path>] to create it.
- Prints shell-specific activation hint.
- list
- Scans ROOT, keeps entries that actually contain a Python interpreter.
- Formats a neat 2-column list of <name> -> <interpreter path>.
- remove
- Deletes the venv directory (shutil.rmtree), logging what happened.
- info
- Runs the venv’s Python with a tiny inline script to emit a JSON blob describing:
- version, implementation, executable, sys.prefix, sys.platform,
- sysconfig.get_paths() (install/layout dirs),
- site-packages paths (if available).
- Prints those fields in a readable form.
- path
- Prints the filesystem path to the venv (handy for scripting).
- run
- Builds a modified environment: prepends <venv>/bin (or Scripts) to PATH and sets VIRTUAL_ENV.
- Executes the command after -- using subprocess.call, returning the same exit code.
- pip
- Runs the venv’s pip directly, forwarding all remaining args (install, uninstall, show, etc.).
- freeze/export/import
- freeze runs pip freeze.
- export writes pip freeze output to a file (-o).
- import installs packages from a requirements file (-r).
- CLI wiring
- Uses argparse subcommands.
- Each subcommand sets func=cmd_*, and main() simply parses and dispatches to that function.
Cross-platform notes
- Activation strings are different:
- Linux/macOS: source <venv>/bin/activate
- Windows (cmd/PowerShell): <venv>\Scripts\activate
- Running commands uses PATH injection, so venvman run myenv -- python -V resolves to the venv’s Python.
- The info command asks the venv’s own interpreter for details, which is robust across platforms and Python versions.
