Run python -c "import my_module; my_module.my_func('arg1', 42)" from your terminal for an instant one-liner without modifying the file, or add an if __name__ == "__main__": entry point using argparse (built-in) or typer / click so users can invoke functions cleanly as CLI subcommands (python my_module.py my-func arg1 42).
Basic Example
# math_utils.py
def add(a: int, b: int) -> int:
result = a + b
print(result)
return result
def greet(name: str, excited: bool = False) -> None:
suffix = "!" if excited else "."
print(f"Hello, {name}{suffix}")
# 1. Recommended (Zero code changes — invoke any function directly via `python -c`):
python -c "import math_utils; math_utils.add(10, 25)"
# Output: 35
python -c "import math_utils; math_utils.greet('Sara', excited=True)"
# Output: Hello, Sara!
# 2. If the script lives inside a package (`pkg/math_utils.py`), run from the project root:
python -c "from pkg.math_utils import add; add(10, 25)"
# Output: 35
Key Details & Edge Cases
- Always guard top-level code with
if __name__ == "__main__"::- When you run
python -c "import my_module; my_module.fn()", Python executes every unguarded top-level statement insidemy_module.pyupon import. Wrapping script-level execution insideif __name__ == "__main__":ensures importing the module only defines functions without triggering unintended side effects.
- When you run
- Quote-escaping rules across shells (
bash/zshvs. Windowscmd.exevs. PowerShell):- On macOS/Linux (
bash/zsh), wrap the Python snippet in double quotes"..."and use single quotes'...'for Python strings inside it (python -c "import app; app.run('prod')"). - On Windows
cmd.exe, single quotes do not group arguments—always wrap the entire-cargument in outer double quotes and escape inner double quotes as\"(python -c "import app; app.run(\"prod\")").
- On macOS/Linux (
- Dynamic function dispatch via
sys.argv+getattr()(zero external dependencies):- When exposing multiple functions in a file to shell scripts or Makefiles without writing boilerplate parsers, dispatch by function name at the bottom of your module:
import sys if __name__ == "__main__": func_name, *args = sys.argv[1:] globals()[func_name](*args) # Usage: python math_utils.py greet Sara - Note that
sys.argvpasses all CLI arguments asstr, so cast numeric arguments (int(a)) inside the function or useargparse/typer.
- When exposing multiple functions in a file to shell scripts or Makefiles without writing boilerplate parsers, dispatch by function name at the bottom of your module:
- Zero-boilerplate CLI generation (
python-fireortyper):- For frequent CLI usage with automatic
--helpflags and type conversion from type hints,python-fire(pip install fire) turns any existing file into a full CLI with two lines (import fire; fire.Fire()$\rightarrow$python math_utils.py add 10 25orpython math_utils.py greet --name=Sara --excited).
- For frequent CLI usage with automatic
- Module search path (
ModuleNotFoundError) when running from another directory:python -cadds the current working directory ("") tosys.path. Ifmy_module.pyresides in another folder, eithercdinto that folder first or prefix withPYTHONPATH=/path/to/dir python -c "import my_module; my_module.fn()".
Comparison of Ways to Call a Specific Python Function from the CLI
| Method | Requires Editing the .py File? |
Automatic Type Casting (int, bool)? |
Generates --help & Tab Completion? |
Best Used When |
|---|---|---|---|---|
python -c "import mod; mod.fn(...)" (Recommended for ad-hoc calls) |
No (just needs if __name__ == "__main__": guard) |
Yes (writes valid Python literals directly) | No | One-off debugging, quick testing, Makefiles, or calling functions in existing libraries. |
argparse / sys.argv under if __name__ == "__main__": |
Yes | Yes (type=int in argparse) |
Yes (argparse builds -h / --help) |
Production scripts and internal tools where zero third-party dependencies are required. |
typer / click (pip install typer) |
Yes (decorators or typer.run(fn)) |
Yes (infers types directly from Python type hints) | Yes (rich help text + shell completion) | Building polished, maintainable multi-command CLI applications. |
python -m fire / fire.Fire() (pip install fire) |
Minimal (or python -m fire math_utils add 10 25 with zero edits!) |
Yes (auto-parses literals from CLI flags) | Yes | Exposing every function and class in a module as CLI subcommands instantaneously. |
You must log in or register to comment.
