[Tutor] IndexError:list index out of range

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Mon, 17 Dec 2001 12:20:53 -0800 (PST)


On Mon, 17 Dec 2001 DavidCraig@pia.ca.gov wrote:

> 
> I am using Idle on WIN 98.  I have the following program:
> 
> ######################################################
> #split and interactively page a string or file of text;
> ######################################################
> 
> import string
> 
> def more(text, numlines=15):
>     lines=string.split(text, '\n')
>     while lines:
>         chunk=lines[:numlines]
>         lines=lines[numlines:]
>         for line in chunk:print line
>         if lines and raw_input('More?') not in ['y', 'Y']:break
> 
> if __name__=='__main__':
>     import sys                           #when run, not imported
>     more(open(sys.argv[1]).read(), 10)   #page contents of file on cmdline
> 
> Every time I try to run it I get the following error message.
> 
> raceback (most recent call last):
>   File "C:/Python21/Practice/more.py", line 17, in ?
>     more(open(sys.argv[1]).read(), 10)   #page contents of file on cmdline
> IndexError: list index out of range


The error's probably referring to the 'sys.argv[1]' part of that line:
that part is trying to get at the 2nd argument given from a command line.  
However, since we're running this from IDLE, and since we haven't
specified a command line, the sys.argv list is probably empty.


According to the IDLE documentation at:

    http://www.python.org/idle/doc/idle2.html

"""
You can of course also test files that are being developed to actually be
scripts in this way as well. You can't currently set command line options
and parameters when you invoke the Run script command. However, during
development you can always instrument your code with a simple test
function that sets sys.argv to any desired value (simulating a command
line invocation) before calling your regular top level script function.
"""


It sounds like it recommendsy hardcoding a sys.argv value while testing
the rest of your program out.  Does anyone know a better solution?