python command-line arguments

I know it's not glamorous, but a basic need for any program is the ability to handle command-line arguments. Every CLI program seems to have extensive information on usage if you don't provide the right arguments, and it would be a good idea to provide your own users the same courtesy. So with just a couple of lines, as seen below, you will be able to expand your program with the ability to receive command-line args, and gracefully handle missing arguments.

So let's say you need the user to provide a filename and an action of some sort. You would use something like this:

PYTHON:
  1. import sys, time
  2.  
  3. try:
  4.     file = sys.argv[1:][0]
  5.     action = sys.argv[1:][1]
  6. except:
  7.     print "Usage: program.py [file] [action]"
  8.     time.sleep(3)
  9.     sys.exit(0)

It's a BASIC idea, but terribly useful. The script tries to store the two command-line args into variables. If that fails, it displays "Usage" info, waits 3 seconds, and exits.

Leave a Reply