Accept command-line arguments
Separate a command-line entry point from reusable logic.
Jump to the automation labsys.argv holds the command-line arguments as strings. The first item identifies the script, so sys.argv[1:] selects the values a user typed after it. Checking the number of arguments first avoids an IndexError.
When Python runs a file directly, its __name__ is "__main__". When the file is imported, its module name is used instead. Put the entry point behind the guard so importing a function leaves the command-line program idle.
Returning an exit status from main() lets the caller inspect it. By convention, 0 signals success and a nonzero number signals a problem. A terminal script can pass that status to sys.exit().
The shell passes the words after the filename as arguments.
Worked examples
Use a real entry point
Save the script and run the command below. Importing names.main from another file leaves the entry point inactive.
import sys
def main(args):
if not args:
print("Usage: python names.py NAME ...", file=sys.stderr)
return 2
print(f"Names: {', '.join(args)}")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))python names.py Ada GraceRun the example and practice
Sort names case-insensitively before joining them. Run the example with ["grace", "Ada"] and preserve the usage behavior.
Target output
Names: Ada, grace
Exit: 0Show a hint
Use sorted(args, key=str.casefold). The call should leave the original list alone.
Ready
Run your code to see the output here.
Check output also tests your code with additional cases.
The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.
Show one solution
def main(args):
if not args:
print("Usage: python names.py NAME ...")
return 2
ordered_names = sorted(args, key=str.casefold)
print(f"Names: {', '.join(ordered_names)}")
return 0
print(f"Exit: {main(['grace', 'Ada'])}")Automation lab
Preview a command-line sale price
Separate argument parsing into a function so you can try an option in the browser and use the same parser from a terminal.
Ready
Run the example to see the output here.
Remove --discount and its value from the argument list to test the default.
Further reading in Automate the Boring Stuff with Python by Al Sweigart