当var IS最明确定义时,Python NameError

时间:2011-04-22 15:09:26

标签: 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()

确定如果我注释掉cmd变量声明,则代码会运行并正确生成fo文件。如上所述取消注释,我得到了file_name上的NameError未定义(它位于顶部)。如果我在cmd声明的正上方取消注释file_name的第二个声明,它会在self上产生一个NameError。 ''在过去发生这种事情时,这是一个语法错误。我想念它,请帮忙!

当注释掉file_name的第二个声明时:

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

取消注释file_name的第二个声明时:

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

3 个答案:

答案 0 :(得分:2)

神秘的NameErrors可能来自包含不可见控制字符的文件。在unix机器上,您可以通过查看

的输出来发现这些错误
cat -A filename.py

答案 1 :(得分:1)

尝试在每行之后打印file_name,以查看是否有人从命名空间中删除了“file_name”变量。

此外,为了更加pythonic(和效率),使用

file_name = "_".join((self.client_id, self.client_name, self.batch_num))

连接字符串。

答案 2 :(得分:0)

如果您在此处指定file_name

file_name = self.client_id+"_"+self.client_name+"_"+self.batch_num

你得到NameError报告,没有定义file_name,然后尝试将操作包装在try..except中,看看出了什么问题:

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

如果其中任何一项失败,这将使您找到原因,找出原因并缩小原因。