'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



Solution 1:[1]

Use nargs=2:

parser.add_argument(
    '-c',
    '--compare',
    nargs=2,
    metavar=('newfile', 'oldfile'),
    help='Compares previous run results in oldfile with actual 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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1