Pobrałem ten skrypt, aby pomóc mi przekonwertować niektóre PNGS. Jest to jednak z 2003 roku, a po raz pierwszy próbowałem go uruchomić, dało mi błędy dla składni wyjątkowej. Udało mi się to naprawić i uruchomiłem ponownie. Następnie dało mi błędy składni drukowania. Naprawiłem te również. Teraz mam absolutnie nie mam pojęcia, co się dzieje oprócz skryptu, który nie działa.

Skrypt to:

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

Teraz, kiedy uruchomię go w oknie DOS, otrzymuję ten błąd:

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'

Co ja robię?

-1
Kasim Ahmic 9 sierpień 2012, 00:38

3 odpowiedzi

Najlepsza odpowiedź

Możesz przesunąć operator % w nawiasie.

print (" -  %d PNG files were found at this folder (and subfolders)." % len(pngs))
5
Eduardo 8 sierpień 2012, 20:43

W Pythonie 2 literały zwykłe literówki są baktewami, podczas gdy w Pythonie 3 są ciągi Unicode. Jeśli chcesz napisać bano-literal, użyj prefiksu b, np. b "x89png r n x1a". Python 3 jest surowy, jeśli chodzi o mieszanie batyfikacji z ciągami Unicode.

Inne różnice są takie, że w Pythonie 3, {x0}} jest teraz normalną funkcją, a nie oświadczeniem, funkcją range zwraca generator, np. xrange w Pythonie 2, a {{x3} } jest jak raw_input w Pythonie 2 (nie ma odpowiednika funkcji Pythona 2-{X5}} w Pythonie 3 - został upuszczony, ponieważ został uznany za niebezpieczny).

Oto moja próba przetłumaczenia kodu w Python 3 (przypadkowo, przy użyciu from something import * jest zniechęcony, ponieważ może nieumyślnie ukryć wiele nazw; importuj tylko te nazwy, których chcesz użyć):

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)
1
MRAB 8 sierpień 2012, 23:17

Co się stanie, gdy próbujesz% STR (LEN (PNGS))?

-1
verbsintransit 8 sierpień 2012, 21:07