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, 2019 in Python by Madhu
1,182 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, 2019 by Suri

Related Questions In Python

0 votes
2 answers

How do I access command line arguments in Python?

import sys print(sys.argv) More specifically, if you run python example.py ...READ MORE

answered Jun 25 in Python by Karan
92 views
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
344 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 aryya
• 7,380 points
109 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,480 points
67 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, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,365 views
0 votes
0 answers
+4 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,800 points
1,011 views
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, 2019 in Python by SDeb
• 13,250 points
132 views
0 votes
1 answer

how to manage memory in python?

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

answered May 20, 2019 in Python by Mohammad
• 3,210 points
68 views