1

I have a python command line script that may be used in two different ways.

First scenario is like this:

script.py -max MAX -min MIN -delta DELTA

where -max and -min are required arguments and -delta is optional.

The second scenario is:

script.py some_file.txt -f

where some_file.txt is required positional argument and -f is optional.

How do i implement that using any Python command line arguments parser (argparse, optparse, getopt, etc)?

UPDATE: script does only one thing - scrapes a site. But it's very long in time operation. In first case we run new scrape session while in second load earlier saved session and continue scrapping.

3 Answers 3

6

I'd do that this way:

parser = OptionParser()
parser.add_option("-max", dest="max")
parser.add_option("-min", dest="min")
parser.add_option("-delta", dest="delta")
parser.add_option("-f", dest="f_thing", action="store_true")

(options,args) = parser.parse_args()

if not args:
    if not options.max or not options.min:
        parser.error("Please provide a max and min value.")
    else:
        yourfunction(options, args) # without some_file.txt name
else:
        yourfunctions(options, args) # pass the some_file.txt name

I'm not sure, if that's 100% what you want, but I think that this question is a little too close. That would give you some idea, how your goal can be achieved.

Sign up to request clarification or add additional context in comments.

Comments

2

Those two cases seem different enough to me that I would be tempted to use two separate scripts. If they share common code, put that in its own module and import it into each script.

If you do want to use one script, why not use a subparser? Then you'd invoke your script and explicitly tell it what scenario you want, e.g.:

script.py calc -max MAX -min MIN -delta DELTA

or

script.py read some_file.txt -f

(Where 'calc' and 'read' are of course whatever names you want to use for these two functions.)

Comments

0

if you use argparse instead of optparse, you can indicate required arguments separately from optional ones by omitting the '-' before the letter

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('min', help="min value for function")
parser.add_argument('max', help="max value for function")
parser.add_argument('-d','--delta', type=int, help="the delta value")
args = parser.parse_args()

print args

and i can run like this:

$ argtest.py -d 10 5 20
Namespace(delta=10, max='20', min='5')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.