Question

I have one game server. I have one tools and i used this for generate crc32 + timestamp and save to file.. but this script file have more functions and I don't want use them.I need just Get crc32, timestamp and save to file.

I try to delete these functions but not work it give syntax or another error. I tried 100x.. And I want post here, maybe someone can help me..

#!/usr/local/bin/python

from urllib import urlopen
from datetime import date
import sys
import os
import zlib
import getopt
import csv
import zipfile

#
# Utility functions
#

def FindFilesByExt(path, ext):
    ext = ext.lower()

    for root, dirs, files in os.walk(path):
        for name in files:
            if name[-len(ext):].lower() == ext:
                yield os.path.join(root, name)

def GetFileCrc32(filename):
    crc = 0
    for line in open(filename, "rb"):
        crc = zlib.crc32(line, crc)

    return "%x" % (crc & 0xffffffff)

def FormatName(filename):
    if filename[:2] == ".\\":
        filename = filename[2:]

    return filename.replace("\\", "/")

def GetLastModifiedTime(filename):
    # http://support.microsoft.com/kb/167296
    # How To Convert a UNIX time_t to a Win32 FILETIME or SYSTEMTIME
    EPOCH_AS_FILETIME = 116444736000000000  # January 1, 1970 as MS file time
    HUNDREDS_OF_NANOSECONDS = 10000000

    return EPOCH_AS_FILETIME + long(os.path.getmtime(filename)) * HUNDREDS_OF_NANOSECONDS

#
# Real code
#

class Patch:
    def __init__(self):
        self.name = None
        self.patch_url = None

        # Patch file list
        self.file_dict = dict()
        self.file_list = None

    def SetName(self, name):
        self.name = name

    def SetPatchUrl(self, url):
        self.patch_url = url

    def AddFilesFromPatchUrl(self):
        for line in urlopen(self.patch_url):
            line = line.split()
            print line
            line[4] = FormatName(line[4])
            self.file_dict[line[4].lower()] = line

    def AddFile(self, filename):
        filename = FormatName(filename)
        mtime = GetLastModifiedTime(filename)

        #
        # Format is as following:
        # unpacked_crc unpacked_size low_last_edit high_last_edit path
        #

        self.file_dict[filename.lower()] = [GetFileCrc32(filename),
                            "%d" % (os.path.getsize(filename)),
                            "%d" % (mtime >> 32),
                            "%d" % (mtime & 0xffffffff), filename]

        # Sorted list no longer contains all files. Invalidate it.
        self.file_list = None

    def GetCrcList(self):
        self.__SortFileList()

        output = ""
        for entry in self.file_list:
            output += (" ".join(entry) + "\n")

        return output

    def __SortFileList(self):
        if not self.file_list:
            self.file_list = [self.file_dict[key] for key in self.file_dict]
            self.file_list.sort(key=lambda entry: entry[4].lower()) # 4 = filename index


kPatchConfigFieldNames = ["Name", "Url"]

def GetPatchInstance(filename, desiredName):
    with open(filename, 'r') as file:
        reader = csv.DictReader(file, fieldnames=kPatchConfigFieldNames, dialect='excel-tab')
        reader.next()

        for row in reader:
            if row["Name"] == desiredName:
                patch = Patch()
                patch.SetName(row["Name"])
                patch.SetPatchUrl(row["Url"])
                return patch

    raise RuntimeError("Failed to find %s!" % (desiredName))
    return None

def WriteXmlFile(filename, files):
    file = open(filename, "wb+")

    file.write('<ScriptFile>')

    for f in files:
        file.write('\t<CreateLz Input="%s" Output="%s.lz" />\n' % (f, f))

    file.write('</ScriptFile>')

def main(argv):
    #
    # Parse command-line arguments
    #

    optlist, args = getopt.getopt(argv[1:], 'a:f:p:', ['archive=', 'file=', 'patchcfg='])

    archives = list()
    files = list()
    patchConfigName = None

    for name, value in optlist:
        if name == "--archive" or name == "-a":
            files.append("pack/" + value + ".eix")
            files.append("pack/" + value + ".epk")
        elif name == "--file" or name == "-f":
            files.append(value)
        elif name == "--patchcfg" or name == "-p":
            patchConfigName = value

    #
    # Decide over patch-config to use...
    #

    patch = GetPatchInstance("PatchConfig.txt", patchConfigName)

    # Add already existing files
    patch.AddFilesFromPatchUrl()

    # Process files
    WriteXmlFile("make_patch.xml", files)

    os.system("FileArchiver make_patch.xml")

    os.unlink("make_patch.xml")

    # Create patch ZIP
    zip = zipfile.ZipFile("PATCH_%s_%s.zip" % (patchConfigName, date.today().strftime("%m%d%Y")), "w", zipfile.ZIP_DEFLATED)

    for file in files:
        patch.AddFile(file)
        file = file + ".lz"
        zip.write(file)
        os.unlink(file)

    zip.writestr("crclist", patch.GetCrcList())

    zip.close()

main(sys.argv)

If you want to try out this script, run this in the cmd:

python make_patch.py -f filename.extension -p patch_live

For this to run, it needs PatchConfig.txt in same folder

make_patch.py

PatchConfig.txt

Was it helpful?

Solution

When you delete functions from a script, you need to make sure that the function you deleted is not being called later in the code.

For example, let's say your script looks like this:

def foo(x):
    return x*x

def banana():
    return "Peel"

def bar():
    return "My " + banana()

i = int(raw_input("Please enter a number to be squared: "))

print foo(i) #prints the number you entered, squared

print banana() #prints "Peel"

print bar() #prints "My Peel"

So, if I only want the functionality of the functions bar() and foo(x) and I don't need to use the functionbanana(), I can delete these functions. However, if I only delete the function banana(), it will give an error, like so:

def foo(x):
    return x*x

#deleted banana()

def bar():
    return "My " + banana()

i = int(raw_input("Please enter a number to be squared: "))

print foo(i) #prints the number you entered, squared

print banana() #gives an error because banana() is not defined

print bar() #not executed because of the above error.

Let's delete print banana() and see if that fixes it.

def foo(x):
    return x*x

#deleted banana()

def bar():
    return "My " + banana()

i = int(raw_input("Please enter a number to be squared: "))

print foo(i) #prints the number you entered, squared

#deleted print banana()

print bar() #error because the bar() function calls the deleted banana() function

This still does not work, because the bar() function calls banana() here:

def bar():
    return "My " + banana()

When you delete a function, you need to delete every single call to that function, no matter where it is. If not, Python will try to call a function that doesn't exist and will give you an error. The correct example code for removing all traces of banana() is below:

def foo(x):
    return x*x

#deleted banana()

def bar():
    return "My " + "Peel" # removed banana()

i = int(raw_input("Please enter a number to be squared: "))

print foo(i) #prints the number you entered, squared

#deleted print banana()

print bar() #prints "My Peel"

When you apply this to your code, make sure no functions you delete are called directly by any function you want to save (the crc32 function). In my example, if you wanted to keep the bar() function, the banana() function is actually necessary to run bar() so you should not delete it.

In your code, the AddFile method is what you call when you call GetFileCrc32(). As you can see, FormatName() and GetLastModifiedTime() are both called as well. These functions are necessary for GetFileCrc32() to work so you should not delete them.

 def AddFile(self, filename):
    filename = FormatName(filename)
    mtime = GetLastModifiedTime(filename)

    #
    # Format is as following:
    # unpacked_crc unpacked_size low_last_edit high_last_edit path
    #

    self.file_dict[filename.lower()] = [GetFileCrc32(filename),
                        "%d" % (os.path.getsize(filename)),
                        "%d" % (mtime >> 32),
                        "%d" % (mtime & 0xffffffff), filename]

    # Sorted list no longer contains all files. Invalidate it.
    self.file_list = None

I hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top