2012-08-08 115 views
-1

我下載了這個腳本來幫助我轉換一些PNG。然而,從2003年開始,我第一次嘗試運行它,它給了我異常語法的錯誤。我設法修復並再次運行它。然後它給了我打印語法的錯誤。我也修正了這些。除了腳本無法工作外,現在我完全不知道發生了什麼。如何讓這個Python腳本與Python 3一起工作?

的腳本是:

from struct import * 
from zlib import * 
import stat 
import sys 
import os 

def getNormalizedPNG(filename): 
    pngheader = "\x89PNG\r\n\x1a\n" 

    file = open(filename, "rb") 
    oldPNG = file.read() 
    file.close() 

    if oldPNG[:8] != pngheader: 
     return None 

    newPNG = oldPNG[:8] 

    chunkPos = len(newPNG) 

    # For each chunk in the PNG file  
    while chunkPos < len(oldPNG): 

     # Reading chunk 
     chunkLength = oldPNG[chunkPos:chunkPos+4] 
     chunkLength = unpack(">L", chunkLength)[0] 
     chunkType = oldPNG[chunkPos+4 : chunkPos+8] 
     chunkData = oldPNG[chunkPos+8:chunkPos+8+chunkLength] 
     chunkCRC = oldPNG[chunkPos+chunkLength+8:chunkPos+chunkLength+12] 
     chunkCRC = unpack(">L", chunkCRC)[0] 
     chunkPos += chunkLength + 12 

     # Parsing the header chunk 
     if chunkType == "IHDR": 
      width = unpack(">L", chunkData[0:4])[0] 
      height = unpack(">L", chunkData[4:8])[0] 

     # Parsing the image chunk 
     if chunkType == "IDAT": 
      try: 
       # Uncompressing the image chunk 
       bufSize = width * height * 4 + height 
       chunkData = decompress(chunkData, -8, bufSize) 

      except Exception as e: 
       # The PNG image is normalized 
       return None 

      # Swapping red & blue bytes for each pixel 
      newdata = "" 
      for y in xrange(height): 
       i = len(newdata) 
       newdata += chunkData[i] 
       for x in xrange(width): 
        i = len(newdata) 
       newdata += chunkData[i+2] 
        newdata += chunkData[i+1] 
        newdata += chunkData[i+0] 
        newdata += chunkData[i+3] 

      # Compressing the image chunk 
      chunkData = newdata 
      chunkData = compress(chunkData) 
      chunkLength = len(chunkData) 
      chunkCRC = crc32(chunkType) 
      chunkCRC = crc32(chunkData, chunkCRC) 
      chunkCRC = (chunkCRC + 0x100000000) % 0x100000000 

     # Removing CgBI chunk   
     if chunkType != "CgBI": 
      newPNG += pack(">L", chunkLength) 
      newPNG += chunkType 
      if chunkLength > 0: 
       newPNG += chunkData 
      newPNG += pack(">L", chunkCRC) 

     # Stopping the PNG file parsing 
     if chunkType == "IEND": 
      break 

    return newPNG 

def updatePNG(filename): 
    data = getNormalizedPNG(filename) 
    if data != None: 
     file = open(filename, "wb") 
     file.write(data) 
     file.close() 
     return True 
    return data 

def getFiles(base): 
    global _dirs 
    global _pngs 
    if base == ".": 
     _dirs = [] 
     _pngs = [] 

    if base in _dirs: 
     return 

    files = os.listdir(base) 
    for file in files: 
     filepath = os.path.join(base, file) 
     try: 
      st = os.lstat(filepath) 
     except os.error: 
      continue 

     if stat.S_ISDIR(st.st_mode): 
      if not filepath in _dirs: 
       getFiles(filepath) 
       _dirs.append(filepath) 

     elif file[-4:].lower() == ".png": 
      if not filepath in _pngs: 
       _pngs.append(filepath) 

    if base == ".": 
     return _dirs, _pngs 

print ("iPhone PNG Images Normalizer v1.0") 
print (" ") 
print ("[+] Searching PNG files..."), 
dirs, pngs = getFiles(".") 
print ("ok") 

if len(pngs) == 0: 
    print (" ") 
    print ("[!] Alert: There are no PNG files found. Move this python file to the folder that contains the PNG files to normalize.") 
    exit() 

print (" ") 
print (" - %d PNG files were found at this folder (and subfolders).") % len(pngs) 
print (" ") 
while True: 
    normalize = raw_input("[?] Do you want to normalize all images (Y/N)? ").lower() 
    if len(normalize) > 0 and (normalize[0] == "y" or normalize[0] == "n"): 
     break 

normalized = 0 
if normalize[0] == "y": 
    for ipng in xrange(len(pngs)): 
     perc = (float(ipng)/len(pngs)) * 100.0 
     print ("%.2f%% %s") % (perc, pngs[ipng]) 
     if updatePNG(pngs[ipng]): 
      normalized += 1 
print (" ") 
print ("[+] %d PNG files were normalized.") % normalized 

現在,當我在DOS窗口中運行它,我得到這個錯誤:

C:\wamp\www\py>ipin.py 
iPhone PNG Images Normalizer v1.0 

[+] Searching PNG files... 
ok 

- %d PNG files were found at this folder (and subfolders). 
Traceback (most recent call last): 
    File "C:\wamp\www\py\ipin.py", line 158, in <module> 
    print (" - %d PNG files were found at this folder (and subfolders).") % len(pngs) 
TypeError: unsupported operand type(s) for %: 'NoneType' and 'int' 

我該怎麼辦?

+0

您是否嘗試過運行[ 2to3](http://docs.python.org/library/2to3.html)?你也可以安裝python的2.7版本,這是大多數人使用的。 – Josiah 2012-08-08 20:40:52

+0

是否有可能獲得一些記錄統計有多少人使用每個版本的Python? – 2012-08-08 20:51:08

+0

@NoctisSkytower據我所知,不,我僅僅從傳聞的證據中說,因爲我從來沒有真正遇到過使用Python 3的人,並且看起來這裏的很少的問題似乎使用Python 3。 – Josiah 2012-08-08 21:02:45

回答

5

您可能需要將括號內的%運算符移開。

print (" - %d PNG files were found at this folder (and subfolders)." % len(pngs)) 
+0

Now我得到這些錯誤: '$ ipin.py ./ipin.py:line 25:from:command not found ./ipin.py:line 26:from:command not found ./ipin.py:line 27 :import:command not found ./ipin.py:line 28:import:command not found ./ipin.py:line 29:import:command not found ./ipin.py:line 31:接近意外的語法錯誤令牌'(' ./ipin.py:第31行:'def getNormalizedPNG(filename):'' – 2012-08-08 20:54:58

+0

對不起,我真的不用markdown多:/ 無論如何,使用2to3,我得到了這個錯誤:/ bin/env:python:沒有這樣的文件或目錄 – 2012-08-08 21:44:10

-1

當您嘗試%str(len(pngs))時會發生什麼?

+0

這不是一個答案(顯然不是一個意圖);請刪除它。 – bignose 2015-12-30 10:43:26

1

在Python 2中,純字符串文字是字節串,而在Python 3中,它們是Unicode字符串。如果要編寫字節串文字,請使用b前綴(例如, B 「\ x89PNG \ r \ n \ X1A \ n」 個。當涉及到將字符串與Unicode字符串混合時,Python 3是嚴格的。

其他方面的差異是在Python 3,print現在是一個正常的功能,而不是一個說法,range功能在Python 2返回一個發電機,像xrange,那input就像在Python 2 raw_input(有沒有等效在Python 3中Python 2的input函數 - 因爲它被認爲是不安全的而被刪除)。

這是我嘗試翻譯的代碼到Python 3的(順便說一句,使用from something import *氣餒,因爲這可能會不小心隱藏許多名字;進口只有你想使用這些名稱):

from struct import * 
from zlib import * 
import stat 
import sys 
import os 

def getNormalizedPNG(filename): 
    pngheader = b"\x89PNG\r\n\x1a\n" 

    file = open(filename, "rb") 
    oldPNG = file.read() 
    file.close() 

    if oldPNG[:8] != pngheader: 
     return None 

    newPNG = oldPNG[:8] 

    chunkPos = len(newPNG) 

    # For each chunk in the PNG file  
    while chunkPos < len(oldPNG): 

     # Reading chunk 
     chunkLength = oldPNG[chunkPos:chunkPos+4] 
     chunkLength = unpack(">L", chunkLength)[0] 
     chunkType = oldPNG[chunkPos+4 : chunkPos+8] 
     chunkData = oldPNG[chunkPos+8:chunkPos+8+chunkLength] 
     chunkCRC = oldPNG[chunkPos+chunkLength+8:chunkPos+chunkLength+12] 
     chunkCRC = unpack(">L", chunkCRC)[0] 
     chunkPos += chunkLength + 12 

     # Parsing the header chunk 
     if chunkType == b"IHDR": 
      width = unpack(">L", chunkData[0:4])[0] 
      height = unpack(">L", chunkData[4:8])[0] 

     # Parsing the image chunk 
     if chunkType == b"IDAT": 
      try: 
       # Uncompressing the image chunk 
       bufSize = width * height * 4 + height 
       chunkData = decompress(chunkData, -8, bufSize) 

      except Exception as e: 
       # The PNG image is normalized 
       return None 

      # Swapping red & blue bytes for each pixel 
      newdata = b"" 
      for y in range(height): 
       i = len(newdata) 
       newdata += chunkData[i] 
       for x in range(width): 
        i = len(newdata) 
        newdata += chunkData[i+2] 
        newdata += chunkData[i+1] 
        newdata += chunkData[i+0] 
        newdata += chunkData[i+3] 

      # Compressing the image chunk 
      chunkData = newdata 
      chunkData = compress(chunkData) 
      chunkLength = len(chunkData) 
      chunkCRC = crc32(chunkType) 
      chunkCRC = crc32(chunkData, chunkCRC) 
      chunkCRC = (chunkCRC + 0x100000000) % 0x100000000 

     # Removing CgBI chunk   
     if chunkType != b"CgBI": 
      newPNG += pack(">L", chunkLength) 
      newPNG += chunkType 
      if chunkLength > 0: 
       newPNG += chunkData 
      newPNG += pack(">L", chunkCRC) 

     # Stopping the PNG file parsing 
     if chunkType == b"IEND": 
      break 

    return newPNG 

def updatePNG(filename): 
    data = getNormalizedPNG(filename) 
    if data != None: 
     file = open(filename, "wb") 
     file.write(data) 
     file.close() 
     return True 
    return data 

def getFiles(base): 
    global _dirs 
    global _pngs 
    if base == ".": 
     _dirs = [] 
     _pngs = [] 

    if base in _dirs: 
     return 

    files = os.listdir(base) 
    for file in files: 
     filepath = os.path.join(base, file) 
     try: 
      st = os.lstat(filepath) 
     except os.error: 
      continue 

     if stat.S_ISDIR(st.st_mode): 
      if not filepath in _dirs: 
       getFiles(filepath) 
       _dirs.append(filepath) 

     elif file[-4:].lower() == ".png": 
      if not filepath in _pngs: 
       _pngs.append(filepath) 

    if base == ".": 
     return _dirs, _pngs 

print ("iPhone PNG Images Normalizer v1.0") 
print (" ") 
print ("[+] Searching PNG files..."), 
dirs, pngs = getFiles(".") 
print ("ok") 

if len(pngs) == 0: 
    print (" ") 
    print ("[!] Alert: There are no PNG files found. Move this python file to the folder that contains the PNG files to normalize.") 
    exit() 

print (" ") 
print (" - %d PNG files were found at this folder (and subfolders)." % len(pngs)) 
print (" ") 
while True: 
    normalize = input("[?] Do you want to normalize all images (Y/N)? ").lower() 
    if len(normalize) > 0 and (normalize[0] == "y" or normalize[0] == "n"): 
     break 

normalized = 0 
if normalize[0] == "y": 
    for ipng in range(len(pngs)): 
     perc = (float(ipng)/len(pngs)) * 100.0 
     print ("%.2f%% %s" % (perc, pngs[ipng])) 
     if updatePNG(pngs[ipng]): 
      normalized += 1 
print (" ") 
print ("[+] %d PNG files were normalized." % normalized) 
+0

我得到這個: $ ipin_py.py ./ipin_py.py:線路1:從:找不到命令 ./ipin_py.py:線路2:從:找不到命令 ./ipin_py.py:3號線:import:command not found ./ipin_py。py:line 4:import:command not found ./ipin_py.py:line 5:import:command not found ./ipin_py.py:line 7:語法錯誤附近出現意外的標記'(' ./ipin_py.py:第7行:'def getNormalizedPNG(filename):' – 2012-08-09 14:19:00

+0

什麼是'$'?你還在Windows上運行它嗎?我問,因爲它在我看來並不認爲它是Python腳本。在沒有shebang行'#!/ usr/bin/python'的Linux上運行它(shebang的細節可能會有所不同)。 – MRAB 2012-08-09 15:03:04

相關問題