2012-08-08 71 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

相关问题