try import except want lineno from Exception

Ben Gerblich benji_75 at hotmail.com
Thu Sep 19 00:23:39 EDT 2002


I am importing module files, and want to catch an error (if any) and
print the filename and line number of the error.
The "Exception ,e" does not return, or does not have the attirbutes listed 
above. It only returns e="line() takes exactly 2 arguments (3 given)"

I think I want to use SyntaxError as it has the attributes: filename, 
lineno, offset and text.
I have found no info on traceback.
With the code below, how do I find the **line_number**?
Thanks.
--<snip>--
[13:45:40]~/py/dev/import2:cat runme.py
from progfile import *

[13:45:44]~/py/dev/import2:cat progfile.py
class Foo:
    def __init__(self):
        self.lines = []

    def line(self,x):
        self.lines.append( x )

print 'start'
try:
    klass = __import__('module')
    code = "object = klass.%s()" % 'Bar'
    exec code
except TypeError, e:
    print 'TypeError\n%s' % e
except Exception, e:
    print 'Exception\n%s' % e
print 'end'

[13:45:51]~/py/dev/import2:cat module.py
from progfile import Foo

class Bar(Foo):
    def __init__(self):
        Foo.__init__(self)
        print 'line-1'; self.line(20)
        print 'line-2'; self.line(40,60) # <--- an error!!!
        print 'line-3'; self.line(80)

[13:45:57]~/py/dev/import2:python2 runme.py
start
line-1
line-2
TypeError
line() takes exactly 2 arguments (3 given)
end

[13:46:07]~/py/dev/import2:


_________________________________________________________________
Join the world’s largest e-mail service with MSN Hotmail. 
http://www.hotmail.com





More information about the Python-list mailing list