John Amraph
John Amraph

Reputation: 461

Python: skipping if the last sys.argv is empty

I run the script: python script.py arg1 arg2, but I want to do the trick, if the arg3 is provided then do something. Current code looking like this, but doesn't work.

if len(sys.argv) == 3:
    pannot = open(sys.argv[3],"w")
    for v in anno2.values():
        pannot.write("\t".join(v))
        pannot.write("\n")
    pannot.close()
else: print("if you want to get an annotation, please, provide third argument")

The error is following: IndexError: list index out of range. Can you please suggest what is the problem? (script was tested under windows).

Upvotes: 0

Views: 5478

Answers (3)

Chris Clarke
Chris Clarke

Reputation: 2181

Quite simply, sys.argv contains the name of the script and the arguments, so len(sys.argv) will be number of arguments + 1. So a simple script:

import sys
print len(argv)

gives:

$ python script.py
1
$ python script.py arg1 arg2 arg3
4

Upvotes: 0

Sukrit Kalra
Sukrit Kalra

Reputation: 34493

To access the last element, use sys.argv[-1]. Or sys.argv[2] in your case. Lists have zero based indices. So, for a list of length 3, the last element would be at testList[2].

If you want to check if the third argument was provided or not, you need to test for a length of 4.

C:\Python27>python scriptName.py 123 456 789
['scriptName.py', '123', '456', '789']

The first argument is the script name, so if you need to see how many additional arguments were passed, you need to check if len(sys.argv) == 4 and then access the last element using sys.argv[-1].

A test program to check that by testing the length of sys.argv would be.

import sys

if len(sys.argv) == 4:
    print "4 arguments were provided. The arguments were :", sys.argv[1:]
elif len(sys.argv) == 3:
    print "3 Arguments were provided. The arguments were :", sys.argv[1:]

Output :

C:\Python27>python scriptName.py 123 456 789
4 arguments were provided. The arguments were : ['123', '456', '789']

C:\Python27>python scriptName.py 123 456
3 Arguments were provided. The arguments were : ['123', '456']

Upvotes: 2

Emil Davtyan
Emil Davtyan

Reputation: 14089

I believe it is because script.py is being passed as the first argument, so you should check :

if len(sys.argv) == 4:

Because the are four arguments :

['script.py', arg1, arg2, arg3]

Here is some working code :

emil ~/test > python script.py arg1 arg2 arg3
arg3
emil ~/test > cat script.py 
import sys
if len(sys.argv) == 4:
    print sys.argv[3] # do something
else:
    print("Please, provide third argument")
emil ~/test > python script.py arg1 arg2
Please, provide third argument

Upvotes: 3

Related Questions