SAM
SAM

Reputation: 105

Multiple Command Line Arguments in Python

In my python script, I am reading one text file. For that file, I am giving path to command line in UNIX as follows:

   python My_script.py --d /fruit/apple/data1.txt

I am going to read one more file in same script. So I just wanted to know how to pass 2 arguments to get path to 2 files. I have following code which is working perfectly for one argument.

parser=argparse.ArgumentParser()
parser.add_argument('--d', '--directory', required=True, action='store', dest='directory', default=False, help="provide directory name")
args=parser.parse_args()
file_apple=args.directory
A=open(file_apple)
file1=A.read()

so in my unix command line I write following and script runs successfully

python My_script.py --d /fruit/apple/data1.txt

Goal is to provide second argument as follows and want to read that file as the first one.

python My_script.py --d /fruit/apple/data1.txt --d /fruit/orange/data2.txt

I will appreciate your help on this.

Upvotes: 2

Views: 4035

Answers (1)

avi
avi

Reputation: 9626

You can make use of nargs.

parser=argparse.ArgumentParser()
parser.add_argument('-d', '--directory', nargs='+' required=True, action='store', dest='directory', default=False, help="provide directory name")
args=parser.parse_args()
file_apple=args.directory
print file_apple
...

I have given nargs value as + which means 1 or many arguments for that command. So, you have to give at least one file path argument.

If you are sure that you are going to have only two or some fixed number always, then you can specify that also like nargs = 3

Now file_apple will be a variable containing list of paths you passed.

$ python My_script.py -d /fruit/apple/data1.txt
['/fruit/apple/data1.txt']

and:

$ python My_script.py -d /fruit/apple/data1.txt /fruit/orange/data2.txt
['/fruit/apple/data1.txt', '/fruit/orange/data2.txt']

PS: conventionally single dash is used for single character flags and doubledash for multi characters. like -d or --directory

Upvotes: 3

Related Questions