The most pythonic way of accepting arguments using optparse

I currently have a python file that uses sys.argv [1] to accept a line on the command line. Then it performs operations on this line and then returns the modified line to the command line.

I would like to implement a batch mode parameter in which I can provide a string file (one per line, fwiw) and return it to the command line so that I can redirect the output by doing something like

$ python script.py -someflag file.txt > modified.txt 

while maintaining current capabilities.

I use only 2.6, so argparse is not an option. The tutorials I saw either use argparse, getopt, or delve into examples that are too complex / not applicable.

What is the best way to check input and act accordingly?

+5
source share
2 answers

argparse is still an option, it just isn't built in 2.6. You can still install it like any third-party package (for example, using easy_install argparse).

An example code for this might be:

import sys
import argparse

p = argparse.ArgumentParser(description="script.py")
p.add_argument("-s", dest="string")
p.add_argument("-f", dest="infile")

args = p.parse_args()

if args.infile == None and args.string == None:
    print "Must be given either a string or a file"
    sys.exit(1)
if args.infile != None and args.string != None:
    print "Must be given either a string or a file, not both"
    sys.exit(1)
if args.infile:
    # process the input file one string at a time
if args.string:
    # process the single string
+6
source

See my answer here: What is the best way to capture / parse command line arguments passed to a Python script?

Here's a sample code as a shortcut:

import optparse

parser = optparse.OptionParser()

parser.add_option('-q', '--query',
    action="store", dest="query",
    help="query string", default="spam")

options, args = parser.parse_args()

print 'Query string:', options.query
+3
source

All Articles