How to print the first line from a traceback stack - python

Suppose I am given the following traceback:
Traceback (most recent call last):
File "<wingdb_compile>", line 3, in <module>
File "C:\Python34\lib\ftplib.py", line 419, in login
resp = self.sendcmd('PASS ' + passwd)
File "C:\Python34\lib\ftplib.py", line 272, in sendcmd
return self.getresp()
File "C:\Python34\lib\ftplib.py", line 245, in getresp
raise error_perm(resp)
ftplib.error_perm: 530 Login incorrect.
I have managed to extract the Error details but what has stumped me is how would I extract the line:
File "<wingdb_compile>", line 3, in <module>
I was looking at methods in the trace back package but wondered if any one had experience with that here

The function traceback.format_exc is built primarily for this
This is like print_exc(limit) but returns a string instead of printing to a file.
>>> import traceback
>>> try:
... x = 2/0
... except:
... error = traceback.format_exc()
...
>>> error
'Traceback (most recent call last):\n File "<stdin>", line 2, in <module>\nZeroDivisionError: division by zero\n'
>>> linesoferror = error.split('\n')
>>> linesoferror
['Traceback (most recent call last):', ' File "<stdin>", line 2, in <module>', 'ZeroDivisionError: division by zero', '']
So now you wanted the first line then you can simply use
>>> linesoferror[1]
' File "<stdin>", line 2, in <module>'
Voila! You have what you want
ALERT - Valid for Python 2.4.1 and above

Related

Speech_Recognizer won't recognize

Robot:I'm Listening
Traceback (most recent call last):
File "C:\Users\HP\Documents\Code\nghe.py", line 8, in <module>
you = robot_ear.recognize_google(audio)
File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\speech_recognition\__init__.py", line 858, in recognize_google
if not isinstance(actual_result, dict) or len(actual_result.get("alternative", [])) == 0: raise UnknownValueError()
speech_recognition.UnknownValueError
I want to a robot hear me talk to him but can't

KeyError with custom derived quantity

I have defined a new derived dimension with
[molar_energy] = [energy] / [substance]
However, if I do the following it complains:
>>> UR.get_compatible_units('[molar_energy]')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/cedric/.local/share/virtualenvs/MatDB--uGOYMXa/lib/python3.9/site-packages/pint/registry.py", line 881, in get_compatible_units
equiv = self._get_compatible_units(input_units, group_or_system)
File "/Users/cedric/.local/share/virtualenvs/MatDB--uGOYMXa/lib/python3.9/site-packages/pint/registry.py", line 2082, in _get_compatible_units
ret = super()._get_compatible_units(input_units, group_or_system)
File "/Users/cedric/.local/share/virtualenvs/MatDB--uGOYMXa/lib/python3.9/site-packages/pint/registry.py", line 1835, in _get_compatible_units
ret = super()._get_compatible_units(input_units, group_or_system)
File "/Users/cedric/.local/share/virtualenvs/MatDB--uGOYMXa/lib/python3.9/site-packages/pint/registry.py", line 891, in _get_compatible_units
return self._cache.dimensional_equivalents[src_dim]
KeyError: <UnitsContainer({'[length]': 2, '[mass]': 1, '[substance]': -1, '[time]': -2})
I saw that there is a conversion included in a context but I don't use it. What I am doing wrong?
Thanks for your help
PS: logged issue https://github.com/hgrecco/pint/issues/1418
Just leaving the solution here for anyone who faces this issue as well.
I just added a made-up unit and it worked
# Molar Energy
[molar_energy] = [energy] / [substance]
mol_en = J / mol

FramenetError: Unknown frame

I run:
from nltk.corpus import framenet as fn
fn.frames()
And get the following error:
Traceback (most recent call last):
File "/Users/me/anaconda3/envs/nlp/lib/python3.6/site-packages/nltk/corpus/reader/framenet.py", line 1308, in frame_by_name
elt = XMLCorpusView(locpath, 'frame')[0]
File "/Users/me/anaconda3/envs/nlp/lib/python3.6/site-packages/nltk/corpus/reader/xmldocs.py", line 155, in __init__
encoding = self._detect_encoding(fileid)
File "/Users/me/anaconda3/envs/nlp/lib/python3.6/site-packages/nltk/corpus/reader/xmldocs.py", line 166, in _detect_encoding
with open(fileid, 'rb') as infile:
NotADirectoryError: [Errno 20] Not a directory: '/Users/me/nltk_data/corpora/framenet_v17.zip/framenet_v17/frame/Abandonment.xml'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/me/anaconda3/envs/nlp/lib/python3.6/site-packages/nltk/corpus/reader/framenet.py", line 876, in __repr__
for elt in self:
File "/Users/me/anaconda3/envs/nlp/lib/python3.6/site-packages/nltk/collections.py", line 406, in iterate_from
try: yield self._func(self._lists[0][index])
File "/Users/me/anaconda3/envs/nlp/lib/python3.6/site-packages/nltk/corpus/reader/framenet.py", line 1407, in frame
f = self.frame_by_id(fn_fid_or_fname, ignorekeys)
File "/Users/me/anaconda3/envs/nlp/lib/python3.6/site-packages/nltk/corpus/reader/framenet.py", line 1268, in frame_by_id
return self.frame_by_name(name, ignorekeys, check_cache=False)
File "/Users/me/anaconda3/envs/nlp/lib/python3.6/site-packages/nltk/corpus/reader/framenet.py", line 1310, in frame_by_name
raise FramenetError('Unknown frame: {0}'.format(fn_fname))
nltk.corpus.reader.framenet.FramenetError: Unknown frame: Abandonment
Both the Framenet 1.5 and 1.7 corpora are installed, according to nltk.download()

Python 2.7: Error not caught by exception due to "raise"

Here's my code:
import pandas as pd
df2 = pd.DataFrame()
try:
df_task = df_task.append(df2, ignore_index = True)
except NameError:
df_task = df2
raise
It produces this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 540, in runfile
execfile(filename, namespace)
File "/home/cld_intern/.spyder2/.temp.py", line 12, in <module>
df_task = df_task.append(df2, ignore_index = True)
NameError: name 'df_task' is not defined
The except block is supposed to catch the NameError, but somehow the inclusion of "raise" without specifying the exception to raise produces a NameError. Why is it so?
This runs perfectly:
import pandas as pd
df2 = pd.DataFrame()
try:
df_task = df_task.append(df2, ignore_index = True)
except NameError:
df_task = df2
This runs as expected too:
import pandas as pd
df2 = pd.DataFrame()
try:
df_task = df_task.append(df2, ignore_index = True)
except NameError:
df_task = df2
raise Exception("error message")
With the following traceback:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 540, in runfile
execfile(filename, namespace)
File "/home/cld_intern/.spyder2/.temp.py", line 15, in <module>
raise Exception("error message")
Exception: error message
in python 3:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
NameError: name 'df_task' is not defined
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
NameError: name 'df2' is not defined
in python2.7
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
NameError: name 'df2' is not defined
Are you sure you are using python 2.7?
Like mentioned in the comment, df2 is not defined i guess.

how to use the post_mortem method of pdb?

I am trying to understand how to use the pdb.post_mortem() method.
for this given file
# expdb.py
import pdb
import trace
def hello():
a = 6 * 9
b = 7 ** 2
c = a * b
d = 4 / 0
print(c)
tracer = trace.Trace()
Command prompt
'''
# first Try
λ python -i expdb.py
>>> pdb.post_mortem()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Program Files\Anaconda3\lib\pdb.py", line 1590, in post_mortem
raise ValueError("A valid traceback must be passed if no "
ValueError: A valid traceback must be passed if no exception is being handled
'''
'''
# Second Try
λ python -i expdb.py
>>> pdb.post_mortem(traceback=tracer.run('hello()') )
--- modulename: trace, funcname: _unsettrace
trace.py(77): sys.settrace(None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Program Files\Anaconda3\lib\trace.py", line 500, in run
self.runctx(cmd, dict, dict)
File "C:\Program Files\Anaconda3\lib\trace.py", line 508, in runctx
exec(cmd, globals, locals)
File "<string>", line 1, in <module>
File "expdb.py", line 8, in hello
d = 4 / 0
ZeroDivisionError: division by zero
>>>
The post_mortem method wants a traceback object, not a Trace object. Traceback objects can be acquired from sys.exc_info()[2] inside of an except block, or you can simply call pdb.post_mortem() with no arguments directly (in the except block).
But either way, you must catch the exception before you can debug it.

Categories

Resources