這個問題在這里已經有了答案: 如何在 python 3 中將二進制資料寫入標準輸出? (4 個回答) 昨天關門。
$ /usr/bin/python2 simple.py 200 > out2.pbm
$ /opt/src/Python-3.10.1/bin/python3 simple.py 200 > out3.pbm
$ cmp out2.pbm out3.pbm
out2.pbm out3.pbm differ: byte 304, line 3
python2輸出是正確的。python3 輸出不正確。
這是一個正確的 .pbm 輸出檔案。
simple.py 是
import sys
w = h = x = y = bit_num = 0
byte_acc = 0
i = 0; iterations = 50
limit = 2.0
Zr = Zi = Cr = Ci = Tr = Ti = 0.0
w = int(sys.argv[1])
h = w
sys.stdout.write("P4\n%d %d\n" % (w, h))
for y in range(h):
for x in range(w):
Zr = Zi = 0.0
Cr = (2.0 * x / w - 1.5); Ci = (2.0 * y / h - 1.0)
for i in range(iterations):
Tr = Zr*Zr - Zi*Zi Cr
Ti = 2*Zr*Zi Ci
Zr = Tr; Zi = Ti
if Zr*Zr Zi*Zi > limit*limit:
break
if Zr*Zr Zi*Zi > limit*limit:
byte_acc = (byte_acc << 1) | 0x00
else:
byte_acc = (byte_acc << 1) | 0x01
bit_num = 1
if bit_num == 8:
sys.stdout.write(chr(byte_acc))
byte_acc = 0
bit_num = 0
elif x == w - 1:
byte_acc = byte_acc << (8-w%8)
sys.stdout.write(chr(byte_acc))
byte_acc = 0
bit_num = 0
什么變化可能導致不同的輸出?
uj5u.com熱心網友回復:
我無法在 Python 3.10.1(Windows,64 位)下運行它:
**Traceback (most recent call last):
File ... simple.py", line 39, in <module>
sys.stdout.write(chr(byte_acc))
File ... \lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\x80' in position 0: character maps to <undefined>
chr()如果我更改to的 2 個實體str()(以便它列印出位元組十進制值的字串表示形式),它會在 3.10.1 和 2.7.11 下產生相同的輸出。
因此,您的 Pythonsys.stdout在 Python 3 下使用的任何默認 Unicode 編碼方案都會讓您感到厭煩。
如果我像這樣設定 envar(在您的作業系統下語法可能不同):
set PYTHONIOENCODING=latin-1
然后兩個 Python 使用chr().
單程
這是“修復它”的一種方法:
import sys
from sys import stdout
if hasattr(stdout, "buffer"): # Python >= 3
def putbyte(b):
assert 0 <= b < 256
stdout.buffer.write(bytes([b]))
else: # before Python 3
def putbyte(b):
assert 0 <= b < 256
stdout.write(chr(b))
然后更改您的代碼以使用putbyte(byte_acc)而不是當前的sys.stdout.write(chr(byte_acc)).
不過,這還不夠。自己寫入內部緩沖區也使您負責跨用途的緩沖區管理。在當前
sys.stdout.write("P4\n%d %d\n" % (w, h))
你還需要添加
sys.stdout.flush()
to get the output string into the buffer before you add additional output bytes.
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/449842.html
標籤:Python python-3.x python-2.7 ubuntu
