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]

print "enter the second argument"

It works well for the following command : 

python 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 file1 

It gives the error : 

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

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

Jul 11, 2019 in Python by Madhu

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 ...READ MORE

answered Jun 25, 2020 in Python by Karan
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 in Python by Gitika
• 65,950 points
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
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,440 points
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 2,400 views
0 votes
0 answers
+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,810 points
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
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