-1

I need check if input variable is set, I use python 3.5, example:

./update-stack.py stack-name (with stack-name as argument works)

instead

./update-stack.py (without stack-name i have an error)

Traceback (most recent call last):
  File "update-stack.py", line 22, in <module>
    stack = sys.argv[1]
IndexError: list index out of range

I have write this for check this:

if len(sys.argv) <= 0:
    print('ERROR: you must specify the stack name')
    sys.exit(1)

stack = sys.argv[1]

How to see the print instead error?

Thanks

stecog
  • 2,202
  • 4
  • 30
  • 50

1 Answers1

1

sys.argv has at least one element in it, sys.argv[0] is the script or module name (or -c when using that switch from the command line).

You need to test if you have fewer than 2 elements:

if len(sys.argv) <= 1:

or you could just catch the IndexError exception:

try:
    stack = sys.argv[1]
except IndexError:
    print('ERROR: you must specify the stack name')
    sys.exit(1)

As a side note: I'd print error messages to sys.stderr:

print('ERROR: you must specify the stack name', file=sys.stderr)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343