suverev
suverev

Reputation: 237

Argparse with two values for one argument

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

Upvotes: 20

Views: 22328

Answers (2)

wjandrea
wjandrea

Reputation: 32987

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.

Upvotes: 41

suverev
suverev

Reputation: 237

Wokrs with nargs = '*'

I did following:

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

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

and it works now

Upvotes: 1

Related Questions