Home > Enterprise >  PYTHON - TRY: ARGV STILL ERRORS OUT
PYTHON - TRY: ARGV STILL ERRORS OUT

Time:06-16

Just trying to handle some IndexError while using sys. Searched a lot on how to do it, and I've come to a final "solution", but I don't know why it's not working.

Actual code

#!/usr/bin/python3

import sys

t = sys.argv[1]
u = sys.argv[2]

try:
    t = sys.argv[1]
except IndexError:
    print("no arg 1")

try:
    u = sys.argv[2]
except IndexError:
    print("no arg 2")

Output

Traceback (most recent call last):
  File "/home/try.py", line 9, in <module>
    t = sys.argv[1]
IndexError: list index out of range

I don't know why it errors out, since I have set previously the sys.argv[1] inside the try block

Could anyone help me out on this?

CodePudding user response:

The issue comes from the t and u definitions above the two try blocks. Get rid of those and keep your try blocks and you should be good.

CodePudding user response:

In addition to the spurious statements at the start (i.e. outside of the try statement), I think you are misunderstanding how array subscripting works in Python.

Python arrays start from subscript 0 (not 1). For an array with 2 elements, their subscripts are 0 and 1. So your code should be:

import sys

try:
    t = sys.argv[0]    # <<<
except IndexError:
    print("no arg 1")

try:
    u = sys.argv[1]    # <<<
except IndexError:
    print("no arg 2")

Searched a lot on how to do it ...

Can I point out that this is NOT a good way to learn to program ... or to find the bugs in your code. You should not be searching for "solutions". You should be reading your code, and looking at the evidence and trying to figure out what you have done wrong.

For example, the version of the code in your question actually produces this output:

$ ./test.py 
Traceback (most recent call last):
  File "./test.py", line 5, in <module>
    t = sys.argv[1]
IndexError: list index out of range

It says that the error is on line 5. Then you look at the code and see that line 5 is NOT in the try: statement.

Secondly, you should be consulting reliable resources on Python; e.g. the official documentation, a textbook, or a decent tutorial. They will explain clearly how array subscripts, for example.

  • Related