Python Forum
sys.argv IndexError - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: sys.argv IndexError (/thread-1196.html)



sys.argv IndexError - Blue Dog - Dec-13-2016

What is this error trying to tell me?


Traceback (most recent call last):
  File "C:\Users\renny and kite\Desktop\Python\links\links\links.py", line 8, in
 <module>
_______________________
    base  = sys.argv[1]    (this is the bad line of code)
_____________________________
IndexError: list index out of range
Press any key to continue . . .


RE: new problem, - snippsat - Dec-13-2016

That you should run it from command line(cmd),and not as a script.
The point of sys.argv is getting stuff from command line into python.
#foo.py
import sys

script_name = sys.argv[0]
base  = sys.argv[1] #Give IndexError if not run from command line
print('Name of script <{}>'.format(script_name))
print('Argument from command line <{}>'.format(base))
From cmd python foo.py hello
Output:
Name of script <foo.py> Argument from command line <hello>



RE: new problem, - wavic - Dec-13-2016

Python gets the command line parameters and put them as list in sys.argv. As @snippsat showed you the first index from this list is the script name. If you don't provide any xommand line parameters to the script sys.argv holds only one element with index 0 - the script name. In that case sys.argv[1] doesn't exist.