Python NameError when var IS most definitely defined - python

def make_pdf(self):
self.get_filez()
self.get_client()
file_name = self.client_id+"_"+self.client_name+"_"+self.batch_num
style = libxslt.parseStylesheetDoc(self.xsl_file)
transformation = style.applyStylesheet(self.xml_file,None)
style.saveResultToFilename("tmp/"+file_name+".fo",transformation,0)
style.freeStylesheet()
self.xml_file.freeDoc()
transformation.freeDoc()
fop_cmd = "/usr/bin/xmlgraphics-fop"
#file_name = self.tpa+"_"+self.be+"_"+self.batch_num
cmd = [fop_cmd,"-fo","tmp/"+file_name+".fo","-pdf","tmp/"+file_name+".pdf"]
#fop_transform = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
#fop_log = "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n"
#fop_log = fop_log + time.strftime('%Y-%m-%d %R:%S')+"\n"
#fop_log = fop_log + file_name+".fo" + "\n"
#fop_log = fop_transform.communicate()[0]+"\n"
#f = open("/tmp/error_log","a")
#f.write(fop_log)
#f.close()
OK If I comment out the cmd variable declaration the code runs and makes an fo file correctly. With is uncommented like it is above, I get a NameError on file_name is not defined (which it is in the top). If I uncomment the second declaration of file_name right above the cmd declaratioin, it thows a NameError on self. '.' In the past when this sort of thing happens, it is a syntax error. I am missing it, please helpz!
When the second declaration of file_name is commented out:
Traceback (most recent call last):
File "make_pdfs.py", line 11, in ?
from MakePdfs import MakePdfs
File "/home/khouser/removed/removed/MakePdfs.py", line 16, in ?
class MakePdfs:
File "/home/khouser/removed/removed/MakePdfs.py", line 39, in MakePdfs
cmd = [fop_cmd,"-fo","tmp/"+file_name+".fo","-pdf","tmp/"+file_name+".pdf"]
NameError: name 'file_name' is not defined
When the second declaration of file_name is uncommented:
Traceback (most recent call last):
File "make_pdfs.py", line 11, in ?
from MakePdfs import MakePdfs
File "/home/khouser/removed/removed/MakePdfs.py", line 16, in ?
class MakePdfs:
File "/home/khouser/removed/removed/MakePdfs.py", line 38, in MakePdfs
file_name = self.tpa+"_"+self.be+"_"+self.batch_num
NameError: name 'self' is not defined

Mysterious NameErrors may arise from your file containing invisible control characters. On unix machines, you can spot these errors by looking at the output of
cat -A filename.py

Try to print file_name after each line, to see if somebody is removing the "file_name" variable from your namespace.
In addition, to be more pythonic (and efficient), use
file_name = "_".join((self.client_id, self.client_name, self.batch_num))
to concatenate strings.

If you're assigning file_name here:
file_name = self.client_id+"_"+self.client_name+"_"+self.batch_num
And you're getting a NameError reporting, that file_name is not defined, then try wrapping the operation in a try..except, to see what is going wrong:
try:
file_name = self.client_id+"_"+self.client_name+"_"+self.batch_num
except NameError as err:
print err, 'failed, here is some debug stuff:'
print "CLIENT ID =", self.client_id
print "CLIENT NAME =", self.client_name
print "BATCH NUM =", self.batch_num
If any of this is failing, this will set you on the course to finding out why and narrowing down the cause of it.

Related

How to print line number of error that is inside a function using except in Python?

I want to print an error's line number and error message in a nicely displayed way. The follow is my code, which uses linecache:
import linecache
def func():
if xx == 1:
print('ok')
try:
func()
except:
exc_type, exc_obj, tb = sys.exc_info()
f = tb.tb_frame
lineno = tb.tb_lineno
filename = f.f_code.co_filename
linecache.checkcache(filename)
line = linecache.getline(filename, lineno, f.f_globals)
print_('ERROR - (LINE {} "{}"): {}'.format(lineno, line.strip(), exc_obj))
However, this only gives where the func() is called:
ERROR - (LINE 8 ""): name 'xx' is not defined
Is there a way to print the line number where the error actually occured, which should be Line 4? Or even better, can I print Line 8 and then trace back to line 4? For example, if I do not use try - except, the code:
def func():
if xx == 1:
print('ok')
func()
will give me the following error message, which is much better to locate the error:
File "<input>", line 5, in <module>
File "<input>", line 2, in func
NameError: name 'xx' is not defined. Did you mean: 'xxx'?
You can use traceback and sys modules to get advanced traceback output like you are wishing for.
Here is an example:
import traceback
import sys
def func():
zeroDivide = 1 / 0
try:
func()
except Exception:
print(traceback.format_exc()) # This line is for getting traceback.
print(sys.exc_info()[2]) # This line is getting for the error type.
Output will be:
Traceback (most recent call last):
File "b:\abc\1234\pppp\main.py", line 10, in <module>
func()
File "b:\abc\1234\pppp\main.py", line 7, in func
zeroDivide = 1 / 0
ZeroDivisionError: division by zero
You can use the traceback module to get the line number of the error,
import traceback
def function():
try:
# code
except:
tb_list = traceback.extract_tb(sys.exc_info()[2])
line_number = tb_list[-1][1]
print("An error occurred on line:", line_number)
You can use the traceback.extract_tb() function. This function returns a list of traceback objects, each of which contain information about the stack trace. The last element of this list, tb_list[-1], holds information about the line where the exception occurred. To access the line number, you can use the second element of this tuple, tb_list[-1][1]. This value can then be printed using the print() function.
To get the line number as an int you can get the traceback as a list from traceback.extract_tb(). Looking at the last item gives you the line where the exception was raised:
#soPrintLineOfError2
import sys
import traceback
def func():
if xx == 1:
print('ok')
try:
func()
except Exception as e:
tb = sys.exc_info()[2]
ss = traceback.extract_tb(tb)
ss1 = ss[-1]
print(ss1.line)
print(ss1.lineno)
Output:
if xx == 1:
6

python: exception inside try doesn't jump to except

I am trying to search within the EU parliment votes' description.
They are standard xml files. So far I noticed 2 versions of the votes' result: where the description is text and where it is an url.
Fails at this file: https://www.europarl.europa.eu/doceo/document/PV-9-2022-09-12-RCV_FR.xml
Works fine on the following file: https://www.europarl.europa.eu/doceo/document/PV-9-2022-07-06-RCV_FR.xml
My problem is not the failure itself (that's why I added the try clause) but that code execution doesn't jump to the except path, just exits here with this: string indices must be integers
Please help, why isn't the error properly handled?
for currentfile in f:
mytree = ET.parse(xmlfiles + "\\" + currentfile)
myroot = mytree.getroot()
dixml = etree_to_dict(myroot)
for votes in dixml['PV.RollCallVoteResults']['RollCallVote.Result']:
try:
title = votes['RollCallVote.Description.Text'] #fails here
titletype = type(title)
if titletype == dict:
title=title['#text']
except :
title = votes['RollCallVote.Description.Text']['a']['#text']
try:
ltitle = title.lower()
except :
print(type(title))
if stringtosearch in ltitle:
print(title,currentfile)
edit:
full trace:
Message=string indices must be integers
Source=...debug.py
StackTrace:
File "...debug.py", line 44, in <module>
title = votes['RollCallVote.Description.Text']
During handling of the above exception, another exception occurred:
File "...debug.py", line 44, in <module>
title = votes['RollCallVote.Description.Text']
File "...debug.py", line 49, in <module> (Current frame)
title = votes['RollCallVote.Description.Text']['a']['#text']
This would happen if there is a new exception raised within your catch block, I would presume specifically the votes object at some point of you accessing it, raises this exception.
Try printing out votes and then each time you access it by indexing print it out you'll see to which extent you can continue accessing it via string index ( votes['string'] ).

Can't run a python script ('str' object is not callable)

I am trying to make a python program, that will help me read notifications log easily.
Here's the code:-
location=open("/home/pika/.cache/xfce4/notifyd/log","rt")
data=location.read()
l_data=list(data) #Contents of log file is in string now, in data variable
x=data.count('app_name')
def rm(start,stop,p_name):
for x in range(start,stop+1):
print(x)
n=p_name(x)
m=l_data.remove(n)
print(m)
data=''
data=data.join(l_data)
for i in range(0,x):
#Time of notification
t_start=data.index('[')
t_end=data.index(']')
t=data[t_start:t_end+1]
print(t)
print('\n')
rm(t_start,t_end,t)
#Name of the application
name_start=data.index('app_name')
name_end=data.index('summary')
name=data[name_start:name_end-1]
print(name)
print('\n')
rm(name_start,name_end,name)
#Heading of notification
head_start=data.index('body')
head_end=data.index('app_icon')
head=data[head_start:head_end-1]
print(head)
print('\n')
rm(head_start,head_end,head)
print('-----------------------------------------------------------')
But, it is giving me the following error:-
[2020-07-23T16:24:43]
0
Traceback (most recent call last):
File "New File.py", line 20, in <module>
rm(t_start,t_end,t)
File "New File.py", line 8, in rm
n=p_name(x)
TypeError: 'str' object is not callable
Any idea what's the issue?
(p.s. i am new to programming, sorry for messy code)
p_name is a list. So you need to use square brackets:
n=p_name[x]
You called the function rm() with last parameter p_name as a string.
t=data[t_start:t_end+1] # this is a string
rm(t_start,t_end, t) # t is a string
Inside the function you assign n = p_name(x) which causes the error.
Did you mean n = p_name[x]?

Appending traceback.format_exc() to a list is adding "\" to single quotes (')

I am assigning the stack trace variable traceback.format_exc() to a list as below ,strange thing I notice is after appending ,all the single quotes(') get escaped (\') as can be seen from the output below.
I looked on google #https://github.com/behave/behave/issues/336 and tried to assign (traceback.format_exc(), sys.getfilesystemencoding() which didn't work either,am very curious why is this happening and how to fix this?
import traceback
clonedRadarsdetailslist = []
clonedRadardetails = {}
try:
#raise
(updateproblemoutput,updateproblempassfail) = r.UpdateProblem(problemID=newRadarID, componentName=componentName, componentVersion=componentVersion,assigneeID=assignee,state=state,substate=substate,milestone=milestone, category=category,priority=priority,resolution=re_solution )
except:
clonedRadardetails['updatedFailedReason'] = traceback.format_exc()
clonedRadarsdetailslist.append(clonedRadardetails)
print clonedRadarsdetailslist
OUTPUT:-
['{\'clonedRadar\': 40171867, \'clonedStatus\': \'PASS\', \'clonedRadarFinalStatus\': \'PASS\', \'updatedFailedReason\': \'Traceback (most recent call last):\\n File "./cloneradar.py", line 174, in clone\\n (updatetitleoutput,updatetitlepassfail) = r.UpdateProble(problemID=newRadarID,title=title )\\nAttributeError: \\\'RadarWS\\\' object has no attribute \\\'UpdateProble\\\'\\n\', \'clonedRadarFinalStatusReason\': \'N/A\', \'updateStatus\': \'FAIL\', \'clonedStatusfailReason\': \'N/A\'}', '{\'clonedRadar\': 40171867, \'clonedStatus\': \'PASS\', \'clonedRadarFinalStatus\': \'PASS\', \'updatedFailedReason\': \'Traceback (most recent call last):\\n File "./cloneradar.py", line 174, in clone\\n (updatetitleoutput,updatetitlepassfail) = r.UpdateProble(problemID=newRadarID,title=title )\\nAttributeError: \\\'RadarWS\\\' object has no attribute \\\'UpdateProble\\\'\\n\', \'clonedRadarFinalStatusReason\': \'N/A\', \'updateStatus\': \'FAIL\', \'clonedStatusfailReason\': \'N/A\'}']

Variable not the same type in two different functions

I have two functions which print into an excel file. THe only input is the file name. Here is the code:
#excelpy
import excelpy
#Tinker
from Tkinter import *
from tkSimpleDialog import *
from tkFileDialog import *
Function Mode1
def Mode1(full_name):
print full_name
print type(full_name)
testwbook = excelpy.workbook(full_name)
testwbook.show()
testwbook.set_cell((1,1),'TEST1', fontColor='red')
testwbook.set_range(2,1,['Number','Name'])
m1 = testwbook.save(full_name)
testwbook.close()
return m1
Function Mode2
def Mode2(full_name):
print full_name
print type(full_name)
testwbook = excelpy.workbook(full_name)
testwbook.show()
testwbook.set_cell((1,1),'TEST2', fontColor='red')
testwbook.set_range(2,1,['Number','Name'])
m2 = testwbook.save(full_name)
testwbook.close()
return m2
Main
root = Tk()
d = str(asksaveasfilename(parent=root,filetypes=[('Excel','*.xls')],title="Save report as..."))
d = d + '.xls'
d = d.replace('/','\\')
root.destroy()
Mode1(d)
Mode2(d)
And once in a while I get the following error:
Traceback (most recent call last):
File "T:\TEST\testpy.py", line 2035, in <module>
Mode2(d)
File ""T:\TEST\testpy.py"", line 1381, in Mode2
print type(full_name)
TypeError: 'str' object is not callable
Any idea why is this happening? How can I prevent it?
The only function call in the line you get the error is a call to the built-in function type(), so the only explanation for your error message is that you overwrote the built-in name type by a global name type pointing to a string object. Try adding
print type
before
print type(full_name)
It looks like somewhere you're setting a (global) variable named type to a string, thus overwriting the built-in type function.
Try searching your code for type = to see what turns up.
Understandably, Python would then throw that exception when you tried to call type (strings can't be "called").

Categories

Resources