How to write binary data to stdout in python 3?

前端 未结 4 682
一个人的身影
一个人的身影 2020-11-29 22:26

In python 2.x I could do this:

import sys, array
a = array.array(\'B\', range(100))
a.tofile(sys.stdout)

Now however, I get a TypeErro

4条回答
  •  渐次进展
    2020-11-29 23:31

    An idiomatic way of doing so, which is only available for Python 3, is:

    with os.fdopen(sys.stdout.fileno(), "wb", closefd=False) as stdout:
        stdout.write(b"my bytes object")
        stdout.flush()
    

    The good part is that it uses the normal file object interface, which everybody is used to in Python.

    Notice that I'm setting closefd=False to avoid closing sys.stdout when exiting the with block. Otherwise, your program wouldn't be able to print to stdout anymore. However, for other kind of file descriptors, you may want to skip that part.

提交回复
热议问题