Python 3 TypeError: must be str, not bytes with sys.stdout.write()

前端 未结 2 785
有刺的猬
有刺的猬 2020-11-29 21:59

I was looking for a way to run an external process from python script and print its stdout messages during the execution.
The code below works, but prints no stdout outp

2条回答
  •  無奈伤痛
    2020-11-29 22:43

    While the accepted answer will work fine if the bytes you have from your subprocess are encoded using sys.stdout.encoding (or a compatible encoding, like reading from a tool that outputs ASCII and your stdout uses UTF-8), the correct way to write arbitrary bytes to stdout is:

    sys.stdout.buffer.write(some_bytes_object)
    

    This will just output the bytes as-is, without trying to treat them as text-in-some-encoding.

提交回复
热议问题