2017-11-16 6 views
1

Python3では、私はバイナリモードでstdoutを再オープンしました。その後、私はprint("Hello")と言います。バイトのようなオブジェクトを使う必要があると私に伝えます。十分に公正で、バイナリモードになりました。"バイトのようなオブジェクトが必要です"しかしバイトを使用しています

しかし、私はこれを行うとき:

print(b"Some bytes") 

私はまだこのエラーが出る:それとまでは何

TypeError: a bytes-like object is required, not 'str' 

を?

答えて

4

print()常にと書きます。strの値です。これは、バイトオブジェクトを含め、最初に引数を文字列に変換します。 print() documentationから

:あなたは、バイナリストリーム上で期間をprint()を使用することはできません

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end.

。ストリームに直接書き込むか(.write()メソッドを使用)、またはストリームをTextIOWrapper() objectにラップしてエンコードを処理します。

これらの作業の両方:

import sys 

sys.stdout.write(b'Some bytes\n') # note, manual newline added 

from io import TextIOWrapper 
import sys 

print('Some text', file=TextIOWrapper(sys.stdout, encoding='utf8')) 
関連する問題