user2165857
user2165857

Reputation: 2690

Adding an additional argument to an argparse argument

I'm new to using the arparse module in python and am hoping someone can help me with the following problem. I am specifying a variable number of files as inputs using:

parser = argparse.ArgumentParser(description='Get Files')    
parser.add_argument('-i','--input', help='Input file(s)',required=True, nargs='+') 
args = parser.parse_args()

I would like to specify a variable number of file inputs, each with an associated value of 1 or 2 and am not sure how to do this.

I would like the program to work so that my command line entry should be:

MyProgram.py -i myfile.txt 2 secondfile.txt 1 ...

Once I have this working how do I call each file in the program?

Upvotes: 2

Views: 2260

Answers (4)

chepner
chepner

Reputation: 531055

It would be clearer to have -i once for each pair of inputs, like this:

parser.add_argument("-i", "--input", nargs=2, action='append')

Now, args.input would be a list of lists, like so

 [ ['myfile.txt', 2], ['secondfile.txt', 1] ]

It does require slightly more typing for the user, since -i needs to be explicitly typed once per file.

Another option is to specify each argument as a single word, then parse the word using the type argument. I would get rid of the -i argument as well and use positional arguments for required "options".

parser.add_argument('input', nargs='+', type=lambda x: x.rsplit(":", 2))

Usage would be

myscript.py myfile.txt:1 secondfile.txt:2 ...

Upvotes: 2

Javier Castellanos
Javier Castellanos

Reputation: 9874

Try this:

parser = argparse.ArgumentParser(description='Get Files')    
parser.add_argument('-i','--input', help='Input file(s)',
    required=True, nargs='+', action='append')

args = parser.parse_args()

Upvotes: 0

cjohnson318
cjohnson318

Reputation: 3253

You might be best off using sys.argv as,

import sys, os

variables = list()
filenames = list()

if( len( sys.argv ) > 1 ):
    if( sys.argv[1] == '-i' )or( sys.argv[1] == '--input' ):
        N = len( sys.argv[1:] )
        for i in range( 2, N, 2 ):
            variables.append( int( sys.argv[i] ) )
            filenames.append( sys.argv[i+1] )

for file in filenames:
    # do something here
    os.system( 'less '+file )

I haven't tested this, but that should work.

Upvotes: 0

unutbu
unutbu

Reputation: 879361

Your code is functional. You could use the grouper recipe to loop through args.input two items at a time:

import argparse
parser = argparse.ArgumentParser(description='Get Files')    
parser.add_argument('-i','--input', help='Input file(s)',required=True, nargs='+') 
args = parser.parse_args()
for filename, num in zip(*[iter(args.input)]*2):
    print(filename, num)
    # with open(filename) as f:
    #     ....

yields

('myfile.txt', '2')
('secondfile.txt', '1')

Upvotes: 1

Related Questions