0

I'm getting an error:

'IndexError: list index out of range' for a sys.argv[1] command.

I recognize that sys.argv[0] will give me the name of my file, and in this if-elif-else conditional loop, it clearly routes itself to else, which is undesirable in my current application.

if sys.argv[1] == "train.txt":
    print_data(e2e_train_src, e2e_train_tgt)
elif sys.argv[1] == "valid.txt":
    print_data(e2e_val_src, e2e_val_tgt)
else:
    assert False

I expect the data to print, but it is not the case.

Life is complex
  • 15,374
  • 5
  • 29
  • 58
  • It seems to me that your "elif" should check sys.argv[1] and not sys.argv[0], am I right? – Itai Ganot Apr 07 '19 at 17:29
  • You said you knew `sys.argv[0]` would be the name of the source file, but you are checking it anyway in the second case. When you were testing it, did you pass "valid.txt"? – nickglazer Apr 07 '19 at 17:29
  • "_it clearly routes itself to else_" But you're getting an index error, how is it "clear" in that sense? Perhaps you'd like to check for the length of `sys.argv` first? (e.g. `if len(sys.argv) > 1 and sys.argv[1] == ...`) – TrebledJ Apr 07 '19 at 17:32
  • Possibly related: [sys.argv\[1\], IndexError: list index out of range](https://stackoverflow.com/questions/31689100/sys-argv1-indexerror-list-index-out-of-range) – TrebledJ Apr 07 '19 at 17:33
  • @ItaiGanot, I've edited the code, I want the data to get printed, but I'm unsure of whether/how I should alter/check the indexes to avoid this error – Vedika Parvez Apr 07 '19 at 17:41
  • 1
    If you are getting an `IndexError` then the invocation of your program does not specify `train.txt` or `valid.txt` on the command line. Are you typing `python myprog.py train.txt`? – BoarGules Apr 07 '19 at 17:42

1 Answers1

0

You can check the indexes by doing this:

print("length of arguments: ", len(sys.argv))

This will gives you the amount of arguments.

argv[0] is the python module so it can't be "valid.txt"

Usage of arguments:

$python my_module.py "first_argument" "second_argument"

This will have 2 arguments/parameters.