[EMAIL PROTECTED] wrote: > def main(argv): > try: > optlist, args = getopt.getopt(argv[1:], 'hvo:D:', ['help', > 'verbose']) > except getopt.GetoptError, msg: > sys.stderr.write("preprocess: error: %s" % msg) > sys.stderr.write("See 'preprocess --help'.\n") > return 1 > outfile = sys.stdout > defines = {} > for opt, optarg in optlist: > if opt in ('-h', '--help'): > sys.stdout.write(__doc__) > return 0 > elif opt in ('-v', '--verbose'): > log.setLevel(logging.DEBUG) > elif opt == '-o': > outfile = optarg > elif opt == '-D': > if optarg.find('=') != -1: > var, val = optarg.split('=', 1) > try: > val = eval(val, {}, {}) > except: > pass > else: > var, val = optarg, None > defines[var] = val > > if len(args) != 1: > sys.stderr.write("preprocess: error: incorrect number of "\ > "arguments: argv=%r\n" % argv) > return 1 > else: > infile = args[0] > > try: > preprocess(infile, outfile, defines) > except PreprocessError, ex: > sys.stderr.write("preprocess: error: %s\n" % str(ex))
This is offtopic, but I suggest looking into using optparse_ or argparse_ instead of getopt. This would simplify your code to something like:: parser = argparse.ArgumentParser(description='Preprocess a file.') parser.add_argument('infile', default=sys.stdin, type=argparse.FileType('r')) parser.add_argument('-v', '--verbose', action='store_true') parser.add_argument('-o', dest='outfile', default=sys.stdout, type=argparse.FileType('w')) parser.add_argument('-D', dest='defines', action='append') args = parser.parse_args() if args.verbose is not None: log.setLevel(logging.DEBUG) defines = {} for define in args.define: var, sep, val = define.partition('=') defines[var] = val or None try: preprocess(args.infile, args.outfile, defines) except PreprocessError, ex: sys.stderr.write("preprocess: error: %s\n" % str(ex)) Additionally, if you include your help messages using the help= argument to add_argument(), your usage message will be generated automatically. .. _optparse: http://docs.python.org/lib/module-optparse.html .. _argparse: http://argparse.python-hosting.com/ STeVe -- http://mail.python.org/mailman/listinfo/python-list