How to write binary data to stdout in python 3?

前端 未结 4 692
一个人的身影
一个人的身影 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:12

    In case you would like to specify an encoding in python3 you can still use the bytes command like below:

    import os
    os.write(1,bytes('Your string to Stdout','UTF-8'))
    

    where 1 is the corresponding usual number for stdout --> sys.stdout.fileno()

    Otherwise if you don't care of the encoding just use:

    import sys
    sys.stdout.write("Your string to Stdout\n")
    

    If you want to use the os.write without the encoding, then try to use the below:

    import os
    os.write(1,b"Your string to Stdout\n")
    

提交回复
热议问题