How do I write a Python script with a main block and CLI entry points?

· Category: Python Programming

Short answer

Use if __name__ == "__main__": to run code only when a script is executed directly. Use the argparse module to build robust command-line interfaces without manual sys.argv parsing.

Steps

  1. Define functions that perform the work.
  2. Add a main() function that orchestrates execution.
  3. Parse CLI arguments with argparse.
  4. Guard the main() call with if __name__ == "__main__":.
import argparse

def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

def main():
    parser = argparse.ArgumentParser(description="A simple greeter.")
    parser.add_argument("name", help="Name to greet")
    parser.add_argument("--greeting", default="Hello", help="Greeting text")
    args = parser.parse_args()
    print(greet(args.name, args.greeting))

if __name__ == "__main__":
    main()

Tips

  • The __main__ guard prevents side effects when the file is imported as a module.
  • argparse automatically generates help messages and validates types.
  • Use type=int, type=float, or custom functions to coerce arguments.
  • For complex CLIs, consider click or typer libraries.

Common issues

  • Putting top-level code without the __main__ guard causes it to run on import, which is problematic in tests and imports.
  • argparse exits on --help or invalid arguments, which can surprise unit tests; test the parser logic separately.
  • Forgetting to call parser.parse_args() results in an unused parser object.