Search code examples
python-3.xargvsysindex-error

PYTHON - TRY: ARGV STILL ERRORS OUT


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?

EDIT:

I was able to find a way around for this, which is, a separate script for different stuff.


Solution

  • 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.