How to input optional arguments in python command line

961    Asked by BrianKennedy in Salesforce , Asked on Jul 19, 2021

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?


Answered by bhagwati dubey

In case you are facing python optional arguments then you should definitely use this code.

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


Your Answer

Interviews

Parent Categories