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
7,684 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, 2020 in Python by Karan
1,279 views
0 votes
1 answer

How to prompt for user input and read command-line arguments?

To read user input you can try the cmd module for ...READ MORE

answered Jan 5, 2021 in Python by Gitika
• 65,770 points
1,907 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
1,265 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,460 points
813 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,434 views
0 votes
1 answer
+5 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,790 points
4,070 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,300 points
868 views
0 votes
1 answer

how to manage memory in python?

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

answered May 21, 2019 in Python by Mohammad
• 3,230 points
871 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP