2014-03-27 34 views
0

我有一個遊戲服務器。我有一個工具,我用它來生成crc32 +時間戳並保存到文件..但這個腳本文件有更多的功能,我不想使用它們。我只需要獲取crc32,時間戳並保存到文件。如何在python上刪除函數?

我嘗試刪除這些函數,但不工作它給語法或其他錯誤。我試圖100X ..我想張貼在這裏,也許有人可以幫助我..

#!/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) 

如果你想嘗試一下這個腳本,在cmd運行如下命令:

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

對於這個運行時,它在同一個文件夾需要PatchConfig.txt

make_patch.py

PatchConfig.txt

+0

你可以更具體地說明你嘗試過什麼嗎? – Luigi

+0

@Louis感謝您的關注,它可能禁用其他功能?只需要獲得crc32 +時間戳並將其保存爲「crclist」文件。 我試過刪除功能,但我不能成功,我仍然試圖.. –

回答

0

當您從腳本中刪除功能時,需要確保您刪除的功能是而不是稍後會在代碼中調用。

例如,假設你的腳本是這樣的:

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" 

所以,如果我只想要的功能bar()foo(x)的功能,我並不需要使用的功能banana(),我可以刪除這些功能。不過,如果我只刪除功能banana(),它會給出一個錯誤,就像這樣:

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. 

讓我們刪除print banana(),看看能否解決。

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 

這仍然沒有工作,因爲bar()函數調用banana()這裏:

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

當你刪除一個功能,你需要刪除該功能,每一個呼叫無論身在何處它是。如果沒有,Python會嘗試調用一個不存在的函數,並會給你一個錯誤。去除的banana()所有痕跡正確的示例代碼如下:

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" 

當應用給你的代碼,確保沒有刪除功能直接要保存(CRC32的功能)的任何函數調用。在我的例子中,如果你想保留bar()函數,banana()函數實際上需要運行bar(),所以你不應該刪除它。

在您的代碼中,AddFile方法是您在撥打GetFileCrc32()時調用的方法。如您所見,FormatName()GetLastModifiedTime()也都被調用。這些功能對於GetFileCrc32()工作是必要的,所以你應該不是刪除它們。

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 

我希望這有助於!

+0

謝謝你給我的東西!我嘗試寫入「crclist」文件不是zip,但它給出的錯誤: 'F:\ Metin2ServerFiles \ Clients \ Client_Work \ Metin2Galactica-Released> python make_pa tch.py​​ -f Metin2.exe -p patch_live Traceback文件「make_patch.py​​」,第179行,在 main(sys.argv) 文件「make_patch.py​​」,第175行,主要在 file.writestr(「crclist」,patch。 GetCrcList()) AttributeError:'str'對象沒有屬性'writestr'' –

+0

感謝您的幫助^^我找到了一種方法..我禁用了壓縮完整文件,只是zip **「crclist」**文件:) 'zip = zipfile.ZipFile(「PATCH_%s_%s.zip」% (patchConfigName,date.today()的strftime( 「%米%d%Y」)。), 「W」,zipfile.ZIP_DEFLATED) \t \t 文件在文件: \t \t patch.AddFile(文件) \t \t#文件=文件+ 「.lz」 \t \t#zip.write(文件) \t \t#os.unlink(文件) \t \t zip.writestr( 「crclist」,patch.GetCrcList()) \t \t zip.close()' –

+0

嘗試使用file.write()來代替,這可能有幫助嗎? – Luigi