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
- Define functions that perform the work.
- Add a
main()function that orchestrates execution. - Parse CLI arguments with
argparse. - Guard the
main()call withif __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. argparseautomatically generates help messages and validates types.- Use
type=int,type=float, or custom functions to coerce arguments. - For complex CLIs, consider
clickortyperlibraries.
Common issues
- Putting top-level code without the
__main__guard causes it to run on import, which is problematic in tests and imports. argparseexits on--helpor invalid arguments, which can surprise unit tests; test the parser logic separately.- Forgetting to call
parser.parse_args()results in an unused parser object.