Argparse with two values for one argument

Question:

Now my script calls via:

python resylter.py -n *newfile* -o *oldfile*

code looks like:

parser.add_argument('-n', '--newfile', help='Uses only with -o argument. Compares inputed OLD (-o) file with previous run results with NEW(-n) output.xml file with actual run results')
parser.add_argument('-o', '--oldfile', help='Uses only with -n argument. Compares inputed OLD (-o)  file with previous run results with NEW(-n) output.xml file with actual run results')

and some actions

How i can edit it to use like this?:

python resylter.py -n *newfile* *oldfile*

sys.argv[-1] didn’t works

Asked By: suverev

||

Answers:

Wokrs with nargs = '*'

I did following:

parser.add_argument('-c', '--compare', nargs = '*')

_newfile_ = _args_.compare[0]
_oldfile_ = _args_.compare[1]

and it works now

Answered By: suverev

Use nargs=2:

parser.add_argument(
    '-c',
    '--compare',
    nargs=2,
    metavar=('newfile', 'oldfile'),
    help='Compares previous run results in oldfile with current run results in newfile.',
    )

args = parser.parse_args()

newfile, oldfile = args.compare

Also adding metavar=('newfile', 'oldfile') improves the help text if you run resylter.py -h.

Docs: nargs, metavar

Answered By: wjandrea
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.