command line args

Tim Daneliuk tundra at
Mon Mar 14 22:13:28 CET 2005

joe at wrote:

> Hello,
> I have the following commands:
> testb -s <size>
> testb -s <size> -o <input file>
> testb -s <size> -o <codes>
> How do i split the commands so that all three are valid. And how do i
> check for missing arguments?  
> Thanks,
> -Joe

Look into the getopt module. It vastly simplifies parsing command line
arguments. For example, here is how I use it for handling the passing of
a configuration file, requesting help, or printing the program version.
This bit of code also will look for an environment variable named the
same as the program itself for further args:

#                    Program Entry Point                   #

import getopt
import sys

RCSID="$Id$"              # Will be filled in by RCS checkin.out
CFGFILE="Default.config"  # Default configuration file

def Usage():
     print "Information about proper program command line use."

# Command line processing - Process any options set in the
# environment first, and then those given on the command line

OPTIONS = sys.argv[1:]
envopt = os.getenv(PROGNAME.upper())
if envopt:
     OPTIONS = envopt.split() + OPTIONS

     opts, args = getopt.getopt(OPTIONS, '-f:hv')
except getopt.GetoptError:

for opt, val in opts:
     if opt == "-f":
     if opt == "-h":
     if opt == "-v":
         print RCSID

# Rest of program goes here ....

Tim Daneliuk     tundra at
PGP Key:

More information about the Python-list mailing list