[Tutor] Non type object?

Max Russell max.mail.lists at googlemail.com
Wed Mar 1 12:32:42 CET 2006


I'm trying to debug a script that takes a load of Python files and  checks
them against original text files- it's for checking headers:

#script to verify content of a header is what is should be.

import difflib, os, re, sys

class HeaderChecker(object):
    def __init__(self, directoryPy, directoryTxt, outputFilePath=None):
        """script that reverts the headers from a set of Python files
        and checks them against the original text from a test"""

        self._directoryToCheck = directoryPy
        self._directoryForCompare =directoryTxt
        self._outputFileName = outputFilePath

        # open file to create/clear it
        if self._outputFileName != None:
            outputFile = open(self._outputFileName, "w")
            outputFile.write("Log file for verifying headers")
            outputFile.close()


        # get the contents of the Python directory
        if not os.path.exists(self._directoryToCheck):
            raise ScriptException("Directory %s does not
exist"%self._directoryToCheck)

        fileList = os.listdir(self._directoryToCheck)

        # just look at the python files (make entries with an absolute file
path)
        self._pythonFileList = []
        for file in fileList:
            if file.endswith(".py"):
                self._pythonFileList.append(self._directoryToCheck + "\\" +
file)

        print self._pythonFileList

        if len(self._pythonFileList) == 0:
            raise ScriptException("Directory %s does not contain any python
files "%directoryPy)


        #get the contents of the original text directory for comparison
        if not os.path.exists(self._directoryForCompare):
            raise ScriptException("Directory %s does not
exist"%self._directoryForCompare)

        txtList = os.listdir(self._directoryForCompare)

        self._txtFileList = []
        for item in txtList:
            if item.endswith(".txt"):
                self._txtFileList.append(self._directoryForCompare + "\\" +
item)

        print self._txtFileList

        if len(self._txtFileList)==0:
            raise ScriptException("Directory %s does not contain any python
files "%directoryTxt)

    def getValidPythonFiles(self):
        """
        get valid python files
        """
        self.log(["found %d python files in %s"%(len(self._pythonFileList),
self._directoryToCheck)])
        return self._pythonFileList

    def getTextFiles(self):
        """
        get method for list of text files
        """
        self.log(["found %d text files in %s"%(len(self._txtFileList),
self._directoryForCompare)])
        return self._txtFileList

    def getFileNameFromPath(self, filePath):
        """
        Extract the file name from the file path

        @param  filePath        File path for the python file.
        @return                 File name
        """
        path, file = os.path.split(filePath)
        return file



    def stripFile(self, filetostrip):
        """
        Strips Python files of "#> " commenting
        and removes the code, writes out to a stripped file
        """
        print "\n" + "stripFile is executed" + "\n"
        print ("\n" + filetostrip)
        fh = open(filetostrip, "r")
        filelines = fh.readlines()

        filetostrip = filetostrip.rstrip("py")
        filetostrip = (filetostrip + "strp")
        strippedfile = open(filetostrip, "w")

        for thisline in filelines:
            if thisline.startswith ("#> "):
                thisline.lstrip("#> ")
                strippedfile.write(thisline + "\n")
        strippedfile.close()
        fh.close()

    def compStripToTxt(self, origfile, strippedfile):
        """
        Compares the stripped Python header file
        to the original text of a test
        """
        print "compStripToTxt is executed"
        orig = open(origfile, "r")
        stripped = open(strippedfile, "r")

        origentry = orig.readlines()
        strippedentry = stripped.readlines()
        orig.close()
        stripped.close()

        if origentry != strippedentry:
            d = difflib.Differ()
            variance = list(d.compare(origentry, strippedentry))
            print variance
            return variance
        else:
            return None



    def log(self, linesToLog):
        """
        Log the script output to a file - echo to the console.

        @param  linesToLog     List of strings to write out
        """

        # if we have a output file write to it
        if self._outputFileName != None:
            outputFile = open(self._outputFileName, "a")

            if len(linesToLog) == 0:
                outputFile.write("\n")

            for line in linesToLog:
                outputFile.write(line + "\n")

            outputFile.close()

        # output to shell
        if len(linesToLog) == 0:
            print
        for line in linesToLog:
            print line

######################################
#MAIN SECTION
######################################

if __name__ == "__main__":
    checker = HeaderChecker(sys.argv[1], sys.argv[2], sys.argv[3])

    pythonFileList = checker.getValidPythonFiles()
    checker.log([])
    checker.log(pythonFileList)

    #For all files in the list of Python files, strip the files of the
header
    #comments markings
    changes = []
    for text in checker._txtFileList:
        file1 = checker.getFileNameFromPath(text)
        for pyfile in pythonFileList:
            file2 = checker.getFileNameFromPath(pyfile)
            print "comparing %s to %s"%(file1[:-4], file2[:-3])
            if file1[:-4] == file2[:-3]:
                print "matched %s to %s"%(file1[:-4], file2[:-3])
                pytostrip = checker._directoryToCheck + "\\" + file2
                print pytostrip
                stripped = checker.stripFile(pytostrip)
                print stripped
                #print "\n" + stripped + "\n"
                diff =checker.compStripToTxt(text, stripped)
                print diff
                if diff:
                   # changes.append(diff)
                    print changes
                    break



Now, I have a lot of print statements in there for debugging purposes, but I
don't understand why when I run it, and it parses through my input directory
and comparison directory it returns this

None
compStripToTxt is executed
Traceback (most recent call last):
  File "HeaderChecker.py", line 182, in ?
    diff =checker.compStripToTxt(text, stripped)
  File "HeaderChecker.py", line 114, in compStripToTxt
    stripped = open(strippedfile, "r")
TypeError: coercing to Unicode: need string or buffer, NoneType found



Why is it returning the None type?

How can I fix this?


thanks
Max
--
Max Russell
Senior Test Engineer
Barco
Bonnington Bond, 2 Anderson Place, Edinburgh EH6 5NP, UK
Tel + 44 (0) 131 472 5731 Fax + 44 (0) 131 472 4799
www.barco.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060301/db734e02/attachment.htm 


More information about the Tutor mailing list