How to input optional arguments in python command line?

0 votes

Hi All,

I would like to know how do I make an option file as an argument on command prompt in python. 

At present I using : 

if len(sys.argv) == 3:
first_log = sys.argv[1]
second_log = sys.argv[2]
else:

print "enter the second argument"

It works well for the following command : 

python test.py file1 file2 

However I have another case where only file1 may be present so file1 is mandatory for this script to run however file2 is optionnal :

if len(sys.argv) == 2:
first_log = sys.argv[1]
second_log = sys.argv[2]

pthon test.py file1 

It gives the error : 

second_log = sys.argv[2]
IndexError: list index out of range 

How do I achieve this because if python test.py file1 file2 then I would process both files?

Jul 11 in Python by Madhu
15 views

1 answer to this question.

0 votes

Please use this code.

if len(sys.argv) == 2:
first_log = sys.argv[1]
second_log = sys.argv[2]
answered Jul 11 by Suri

Related Questions In Python

0 votes
1 answer

How to add a new line in Python?

You can use '\n' for a next ...READ MORE

answered May 2, 2018 in Python by aayushi
• 750 points
91 views
0 votes
1 answer

How to read/process command line arguments?

The canonical solution in the standard library ...READ MORE

answered Jun 4, 2018 in Python by ariaholic
• 7,340 points
32 views
0 votes
1 answer

How to read/process command line arguments?

The canonical solution in the standard library ...READ MORE

answered Aug 8, 2018 in Python by bug_seeker
• 15,350 points
24 views
0 votes
1 answer

How to write to CSV line by line in python

The simple way of doing this will ...READ MORE

answered Nov 15, 2018 in Python by findingbugs
• 3,140 points
265 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 232 views
+4 votes
6 answers
0 votes
1 answer

How to read a large file, line by line, in Python?

The correct, fully Pythonic way to read ...READ MORE

answered Jul 1 in Python by SDeb
• 13,160 points
25 views
0 votes
1 answer

how to manage memory in python?

Memory management in python involves a private heap ...READ MORE

answered May 20 in Python by Mohammad
• 3,060 points
18 views