473,761 Members | 10,276 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Pre-defining an action to take when an expected error occurs

Hello. I am getting the error that is displayed below, and I know
exactly why it occurs. I posted some of my program's code below, and if
you look at it you will see that the error terminates the program
pre-maturely. Becasue of this pre-mature termination, the program is
not able to execute it's final line of code, which is a very important
line. The last line saves the Excel spreadsheet. So is there a way to
make sure the last line executes? Thanks in advanced for all of the
help. Thank you.
Error
####

IndexError: list index out of range
Code Sample
###########

for rx in range(sh.nrows) :
rx = rx +1
u = sh.cell_value(r x, 0)
u = str(u)
if u != end:
page = urllib2.urlopen (u)
soup = BeautifulSoup(p age)
p = soup.findAll('s pan', "sale")
p = str(p)
p2 = re.findall('\$\ d+\.\d\d', p)
for row in p2:
ws.write(r,0,ro w)

w.save('price_l ist.xls')

Sep 15 '06 #1
11 2565
On Thu, 14 Sep 2006 19:40:35 -0700, Tempo wrote:
Hello. I am getting the error that is displayed below, and I know
exactly why it occurs. I posted some of my program's code below, and if
you look at it you will see that the error terminates the program
pre-maturely. Becasue of this pre-mature termination, the program is
not able to execute it's final line of code, which is a very important
line. The last line saves the Excel spreadsheet. So is there a way to
make sure the last line executes?
Two methods:

(1) Fix the bug so the program no longer terminates early. You are getting
an IndexError "list index out of range", so fix the program so it no
longer tries to access beyond the end of the list.

I'm guessing that your error is right at the beginning of the loop. You
say:

for rx in range(sh.nrows) :
rx = rx +1

Why are you adding one to the loop variable? That's equivalent to:

for rx in range(1, sh.nrows + 1)

which probably means it skips row 0 and tries to access one row past the
end of sh. If all you want to do is skip row 0, do this instead:

for rx in range(1, sh.nrows)
(2) Stick a band-aid over the error with a try...except block, and hope
you aren't covering up other errors as well. While we're at it, let's
refactor the code a little bit...

# untested
def write_row(rx, sh, end, ws):
u = str(sh.cell_val ue(rx, 0))
if u != end:
soup = BeautifulSoup(u rllib2.urlopen( u))
p = str(soup.findAl l('span', "sale"))
for row in re.findall('\$\ d+\.\d\d', p):
ws.write(r,0,ro w) # what's r? did you mean rx?
Now call this:

for rx in range(sh.nrows) :
rx += 1 # but see my comments above...
try:
write_row(rx, sh, end, ws)
except IndexError:
pass
w.save('price_l ist.xls')

--
Steven D'Aprano

Sep 15 '06 #2
At Thursday 14/9/2006 23:40, Tempo wrote:
>Hello. I am getting the error that is displayed below, and I know
exactly why it occurs. I posted some of my program's code below, and if
you look at it you will see that the error terminates the program
pre-maturely. Becasue of this pre-mature termination, the program is
not able to execute it's final line of code, which is a very important
line. The last line saves the Excel spreadsheet. So is there a way to
make sure the last line executes? Thanks in advanced for all of the
help. Thank you.
You want a try/finally block.
Read the Python Tutorial: http://docs.python.org/tut/node10.html

Gabriel Genellina
Softlab SRL

_______________ _______________ _______________ _____
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Sep 15 '06 #3
Tempo wrote:
Hello. I am getting the error that is displayed below, and I know
exactly why it occurs. I posted some of my program's code below, and if
you look at it you will see that the error terminates the program
pre-maturely. Becasue of this pre-mature termination, the program is
not able to execute it's final line of code, which is a very important
line. The last line saves the Excel spreadsheet. So is there a way to
make sure the last line executes? Thanks in advanced for all of the
help. Thank you.
Error
####

IndexError: list index out of range
[snip]

Hi, Tempo, nice to see xlrd getting some usage :-)

Are you sure that you *really* want to save a spreadsheet written by
your buggy program??? It is better to fix errors, rather than ignore
them.

However, as you asked how: To ensure that cleanup code is executed no
matter what happens, use try/except/finally as in the following
example.

HTH,
John
C:\junk>type tempo.py
import sys

def main(n):
return (10 ** n) / n

try:
try:
print "executing the application ..."
n = int(sys.argv[1])
if n < 0:
# simulate something nasty happening ...
import nosuchmodule
else:
x = main(n)
print "app completed normally: %r" % x
except KeyboardInterru pt:
# need this to escape when n is large
print "kbd interrupt ...."
raise
except ZeroDivisionErr or:
print "doh!"
raise
finally:
# code to be executed no matter what happens
print "finally ... cleaning up"

C:\junk>tempo.p y 0
executing the application ...
doh!
finally ... cleaning up
Traceback (most recent call last):
File "C:\junk\tempo. py", line 14, in ?
x = main(n)
File "C:\junk\tempo. py", line 4, in main
return (10 ** n) / n
ZeroDivisionErr or: integer division or modulo by zero

C:\junk>tempo.p y -1
executing the application ...
finally ... cleaning up
Traceback (most recent call last):
File "C:\junk\tempo. py", line 12, in ?
import nosuchmodule
ImportError: No module named nosuchmodule

C:\junk>tempo.p y 3
executing the application ...
app completed normally: 333
finally ... cleaning up

C:\junk>tempo.p y 10000000000
executing the application ...
kbd interrupt ....
finally ... cleaning up
Traceback (most recent call last):
File "C:\junk\tempo. py", line 14, in ?
x = main(n)
File "C:\junk\tempo. py", line 4, in main
return (10 ** n) / n
KeyboardInterru pt

C:\junk>

Sep 15 '06 #4
Thanks for all of the help. It all has been very useful to an new
python programmer. I agree that I should fix the error/bug instead of
handeling it with a try/etc. However, I do not know why
"range(sh.nrows )" never gets the right amount of rows right. For
example, if the Excel sheet has 10 rows with data in them, the
statement "range(sh.nrows )" should build the list of numbers [0,
1,...9]. It should, but it doesn't do that. What it does is buld a list
from [0, 1...20] or more or a little less, but the point is that it
always grabs empy rows after the last row containing data. Why is that?
I have no idea why, but I do know that that is what is producing the
error I am getting. Thanks again for the responses that I have received
already, and again thanks for any further help. Thanks you.

Sep 15 '06 #5
if the Excel sheet has 10 rows with data in them, the
statement "range(sh.nrows )" should build the list of numbers [0,
1,...9]. It should, but it doesn't do that. What it does is buld a list
from [0, 1...20] or more or a little less, but the point is that it
always grabs empy rows after the last row containing data. Why is that?
Just a stab in the dark, but maybe there's some rogue whitespace in
some cell that's in a rowyou think is empty?

You could try to just select out a (small) region of your data, copy it
and paste it into a new spreadhseet to see if you're still getting the
problem.

-steve

Sep 15 '06 #6
Tempo wrote:
Thanks for all of the help. It all has been very useful to an new
python programmer. I agree that I should fix the error/bug instead of
handeling it with a try/etc. However, I do not know why
"range(sh.nrows )" never gets the right amount of rows right. For
example, if the Excel sheet has 10 rows with data in them, the
statement "range(sh.nrows )" should build the list of numbers [0,
1,...9]. It should, but it doesn't do that. What it does is buld a list
from [0, 1...20] or more or a little less, but the point is that it
always grabs empy rows after the last row containing data. Why is that?
I have no idea why, but I do know that that is what is producing the
error I am getting. Thanks again for the responses that I have received
already, and again thanks for any further help. Thanks you.
So the xlrd package's Book.Sheet.nrow s allegedly "never gets the right
amount of rows right"? Never?? Before making such rash statements in a
public forum [1], you might like to check exactly what you have in your
file. Here's how:

(1) Using OpenOffice.org Calc or Gnumeric (or Excel if you must), open
yourfile.xls and save it as yourfile.csv. Inspect yourfile.csv

(2) Use the runxlrd script that's supplied with xlrd:

runxlrd.py show yourfile.xls >yourfile_show. txt

Inspect yourfile_show.t xt. You'll see things like:
cell A23: type=1, data: u'ascii'
cell B23: type=0, data: ''
cell C23: type=1, data: u'123456'
cell D23: type=0, data: ''
cell E23: type=4, data: 0
The cell-type numbers are in the docs, but briefly: 0 is empty cell, 1
is text, 2 is number, 3 is date, 4 is boolean, 5 is error. If you find
only type=0 in the last row, then indeed you have found a bug and
should report it to the package author (together with a file that
exhibits the problem).

You are likely to find that there are cells containing zero-length
strings, or strings that contain spaces. They *do* contain data, as
opposed to empty cells.

[1] There's a possibility that the package's author reads this
newsgroup, and I've heard tell that he's a cranky old so-and-so; you
wouldn't want him to take umbrage, would you?

HTH,
John

Sep 15 '06 #7
John Machin thanks for all of your help, and I take responsibility for
the way I worded my sentences in my last reply to this topic. So in an
effort to say sorry, I want to make it clear to everybody that it seems
as though errors in my code and use of external programs (Excel in
particular) are making "range(sh.nrows )" have faulty results. I am
trying to pinpoint the spot in my code or use of Excel, before
"range(sh.nrows ) is executed, that is bugged. John Machin, I am
thrilled that the package xlrd exists at all because it simplifies a
daunting task for a beginner programer--me. Its uses are not bound to
beginners either. So thanks for the package and your help to this point.

Sep 15 '06 #8
John Machin wrote:
[...]
>
[1] There's a possibility that the package's author reads this
newsgroup, and I've heard tell that he's a cranky old so-and-so; you
wouldn't want him to take umbrage, would you?
Cranks doesn't even *begin* to describe it ...

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

Sep 15 '06 #9
On 16/09/2006 2:55 AM, Tempo wrote:
John Machin thanks for all of your help, and I take responsibility for
the way I worded my sentences in my last reply to this topic. So in an
effort to say sorry, I want to make it clear to everybody that it seems
as though errors in my code and use of external programs (Excel in
particular) are making "range(sh.nrows )" have faulty results. I am
trying to pinpoint the spot in my code or use of Excel, before
"range(sh.nrows ) is executed, that is bugged. John Machin, I am
thrilled that the package xlrd exists at all because it simplifies a
daunting task for a beginner programer--me. Its uses are not bound to
beginners either. So thanks for the package and your help to this point.
I'm sorry, too: I should have wrapped my post in <humour... </humour>
tags:-)

Of course it's up to you to decide the criteria for filtering out
accidental non-data from your spreadsheet. Note that this phenomenon is
not restricted to spreadsheets; one often sees text data files with
blank or empty lines on the end -- one's app just has to cope with that.

Here's an example of a function that will classify a bunch of cells for you:

def usefulness_of_c ells(cells):
"""Score each cell:
as 0 if empty,
as 1 if zero-length text,
as 2 if text and value.isspace() is true,
otherwise as 3.
Return the highest score found.
"""
score = 0
for cell in cells:
if cell.ctype == xlrd.XL_CELL_EM PTY:
continue
if cell.ctype == xlrd.XL_CELL_TE XT:
if not cell.value:
if not score:
score = 1
continue
if cell.value.issp ace():
score = 2
continue
return 3
return score

and here's an example of using it:

def number_of_good_ rows(sheet):
"""Return 1 + the index of the last row with meaningful data in it."""
for rowx in xrange(sheet.nr ows - 1, -1, -1):
score = usefulness_of_c ells(sheet.row( rowx))
if score == 3:
return rowx+1
return 0

A note on using the isspace() method: ensure that you use it on
cell.value (which is Unicode), not on an 8-bit encoding (especially if
your locale is set to the default ("C")).

| >>'\xA0'.isspac e()
| False
| >>u'\xA0'.isspa ce()
| True
| >>import unicodedata as ucd
| >>ucd.name(u'\x A0')
| 'NO-BREAK SPACE'

You can get these in spreadsheets when folk paste in stuff off a web
page that uses &nbsp; as padding (because HTML trims out
leading/trailing/multiple instances of SPACE). Puzzled the heck out of
me the first time I encountered it until I did:
print repr(data_that_ the_users_were_ shrieking_about )

Here's a tip: repr() in Python and "View Page Source" in Firefox come
in very handy when you have "what you see is not what you've got" problems.

Anyway, I'll add something like the above functions in an examples
directory in the next release of xlrd (which is at alpha stage right
now). I'll also add in a Q&A section in the docs, starting with "Why
does xlrd report more rows than I see on the screen?" -- so do let us
know what you find down the end of your spreadsheet, in case it's a
strange beast that hasn't been seen before.

HTH,
John
Sep 17 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3105
by: GriffithsJ | last post by:
Hi I have been given some text that needs to be displayed on a web page. The text is pre-formatted (includes things like lists etc) and displays okay if I wrap it using the <pre/> tag. However, the font used is rather "naff" and looks too different to the rest of my web page. I'm not sure how I can (or even whether I can) override the font used with the <pre/> tag. If not, is there another tag I can use to display pre-formatted...
21
10222
by: Headless | last post by:
I've marked up song lyrics with the <pre> tag because it seems the most appropriate type of markup for the type of data. This results in inefficient use of horizontal space due to UA's default rendering of <pre> in a fixed width font. To change that I'd have to specify a proportional font family, thereby falling into the size pitfall that is associated with any sort of author specified font family: a) If I specify a sans serif font...
2
3397
by: Jerry Sievers | last post by:
tried to avoid using PRE in the page markup and instead used DIV CLASS=foo and assigned the white-space pre property to it. have some reports already that text is not showing as preformatted. looks ok with mozilla 1.4 though. http://www.jerrysievers.com/Projects/UPSMon/?title=Makefile&file=Makefile comments please.
7
18534
by: Alan Illeman | last post by:
How do I set several different properties for PRE in a CSS stylesheet, rather than resorting to this: <BODY> <PRE STYLE="font-family:monospace; font-size:0.95em; width:40%; border:red 2px solid; color:red;
2
2789
by: Buck Turgidson | last post by:
I want to have a css with 2 PRE styles, one bold with large font, and another non-bold and smaller font. I am new to CSS (and not exactly an expert in HTML, for that matter). Is there a way to do this in CSS? <STYLE TYPE="text/css"> pre{ font-size:xx-large;
5
24113
by: Porthos | last post by:
I'm authoring an XML document and using the <pre> html tag for the portions that are not dynamically generated. The <pre> text is displaying in a smaller font size (and I believe different font) than standard text. I would like all of my text to be formatted this way, though I don't want to use the <pre> tag for all of it. Can anyone tell me what font and size are used by default for the <pre> tag? I don't want to change it's...
1
4741
by: R0bert Nev1lle | last post by:
Here's my next IE challenge (or frustration). It deals with the overflow attribute. Overflow property was a challenge on my page since the page emulates position fixed for IE. The present scenario deals with the pre element. Sometimes the content in the pre container exceed the parent container's width. IE expands the parent containers width as a result. The workaround for this scenario relates to the overflow property and using a...
7
2749
by: Rocky Moore | last post by:
I have a web site called HintsAndTips.com. On this site people post tips using a very simply webform with a multi line TextBox for inputing the tip text. This text is encode to HTML so that no tags will remain making the page safe (I have to convert the linefeeds to <BR>s because the Server.EncodeHTML does not do that it seems). The problem is that users can use a special tag when editing the top to specify an area of the tip that will...
7
4857
by: Paul Connolly | last post by:
char *s = "Hello"; s = 'J'; puts(s); might print "Jello" in a pre-ANSI compiler - is the behaviour of this program undefined in any pre-ANSI compiler - or would it always have printed "Jello" with a pre-ANSI compiler? In gcc with the "writable-strings" option this program prints Jello If there were more than one semantics for what this progran did under a
12
5578
by: Vadim Guchenko | last post by:
Hello. I'm using the following code: <html> <head> <style type="text/css"> pre {display: inline;} </style> </head>
0
9531
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10115
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9905
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8780
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7332
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6609
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5229
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3881
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2752
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.