How do you call a specific Python function directly from the command line? | A1Lab@MZeeshanM to PythonEnglish • 2 days ago

How do you call a specific Python function directly from the command line?

message-square
0

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 inside my_module.py upon import. Wrapping script-level execution inside if __name__ == "__main__": ensures importing the module only defines functions without triggering unintended side effects.
  • Quote-escaping rules across shells (bash/zsh vs. Windows cmd.exe vs. 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 -c argument in outer double quotes and escape inner double quotes as \" (python -c "import app; app.run(\"prod\")").
  • 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.argv passes all CLI arguments as str, so cast numeric arguments (int(a)) inside the function or use argparse / typer.
  • Zero-boilerplate CLI generation (python-fire or typer):
    • For frequent CLI usage with automatic --help flags 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 25 or python math_utils.py greet --name=Sara --excited).
  • Module search path (ModuleNotFoundError) when running from another directory:
    • python -c adds the current working directory ("") to sys.path. If my_module.py resides in another folder, either cd into that folder first or prefix with PYTHONPATH=/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.