Python loves argparse

You have your first handful of lines in your python main. What next?

If you're writing a script you intend to write directly, as opposed to a library of code to reuse, you'll want to accept command-line arguments.

The classic library for this is argparse. There are lots of options, but here is a simple starting example.

import argparse

def main():
  parser = argparse.ArgumentParser(description="My program")
  parser.add_argument("-maxlines", type=int, help="maximum lines to process")
  parser.add_argument("infile", help="file to process")
  parser.add_argument("outfile", help="file to write results to")
  args = parser.parse_args()

if __name__ == '__main__':
  main()

Tell me more

argparse will take care of building help, even if you leave out the help and description values. It will parse the arguments and bail out with a message if something is wrong, otherwise you'll get a neat object with valid values.

There is comprehensive documentation on all the things you can specify in the add_argument() method.

To test your argument parsing, you can pass your own list of strings to parse_args.

If you want simple boolean values, there is a good description on how to achieve that here.

Happy argument parsing!

Tags:  codingpython

Home