command line args

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


joe at gmail.com 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

PROGNAME="MyNiftyProgram"
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

try:
     opts, args = getopt.getopt(OPTIONS, '-f:hv')
except getopt.GetoptError:
     Usage()
     sys.exit(1)

for opt, val in opts:
     if opt == "-f":
         CFGFILE=val
     if opt == "-h":
         Usage()
         sys.exit(0)
     if opt == "-v":
         print RCSID
         sys.exit(0)

# Rest of program goes here ....

-- 
----------------------------------------------------------------------------
Tim Daneliuk     tundra at tundraware.com
PGP Key:         http://www.tundraware.com/PGP/



More information about the Python-list mailing list