Python base64.decode似乎不适用于Windows

时间:2010-06-29 15:18:22

标签: python encoding

我正在使用webservice(用java编写) - 它基本上返回一个byte []数组(SOAP等价物是base64编码的二进制数据)。

我正在使用python suds库,以下代码适用于我的mac(以及windows下的cygwin),但解码不适用于vanilla windows(python 2.6.5)。我主要是一名java开发人员,所以任何帮助都会非常有用。

from suds.client import Client
import base64,os,shutil,tarfile,StringIO

u = "user"
p = "password"

url = "https://xxxx/?wsdl"

client = Client(url, username=u, password=p)

bin =  client.service.getTargz("test")

f = open("tools.tar.gz", "w")

f.write(base64.b64decode(bin.encode('ASCII')))

f.close()

print "finished writing"

tarfile.open("tools.tar.gz").extractall()

在Mac上运行得很好 - 但是在Windows上给了我这个错误:

C:\client>python client.py
xml
Getting the sysprep file from the webservice
finished writing
Traceback (most recent call last):
  File "client.py", line 28, in 
    tarfile.open("tools.tar.gz").extractall()
  File "C:\Python26\lib\tarfile.py", line 1653, in open
    return func(name, "r", fileobj, **kwargs)
  File "C:\Python26\lib\tarfile.py", line 1720, in gzopen
    **kwargs)
  File "C:\Python26\lib\tarfile.py", line 1698, in taropen
    return cls(name, mode, fileobj, **kwargs)
  File "C:\Python26\lib\tarfile.py", line 1571, in __init__
    self.firstmember = self.next()
  File "C:\Python26\lib\tarfile.py", line 2317, in next
    tarinfo = self.tarinfo.fromtarfile(self)
  File "C:\Python26\lib\tarfile.py", line 1235, in fromtarfile
    buf = tarfile.fileobj.read(BLOCKSIZE)
  File "C:\Python26\lib\gzip.py", line 219, in read
    self._read(readsize)
  File "C:\Python26\lib\gzip.py", line 271, in _read
    uncompress = self.decompress.decompress(buf)
zlib.error: Error -3 while decompressing: invalid distance too far back

1 个答案:

答案 0 :(得分:7)

尝试

f = open("tools.tar.gz", "wb")

告诉Python它是一个二进制文件是至关重要的(在Py3中,它在Unixy系统上也变得至关重要,但在Py2中它并不是严格需要它们,这就是为什么你的代码适用于MacOSX ):默认为文本,在Windows上,在写入时将写入\n的每个\r\n转换为磁盘。