Question

I am having an issue. I need to first validate if the python script has at least 2 variables and then check if there is a "-v" option as the first argument. My code keeps throwing an index out of range exception

import sys

if len(sys.argv) >= 2:
    if sys.argv[1]=='-v':
       print('verbose option chosen')
    else:
       print('verbose option not chosen')
else:
    print('not enough variables, try again')
Was it helpful?

Solution

Your're checking the wrong way. You want the first part to execute if sys.argv has at least 2 elements. You want this:

if len(sys.argv) >= 2:

And if you've got some time on your hands, check out the argparse module.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top