Pages

Sunday, 20 December 2020

How to write binary bytes to stdout in Python?

 1 Why is it needed to write bytes to stdout?

While Python's built-in function print() meets most needs, some situations do need to write bytes instead of strings to stdout.
For example, a CGI app generating pictures on the fly needs to write binary picture data into stdout.

2 Solutions

To avoid mixing with the data written by "print()", before binary write, make sure to flush the stdout's buffer.

2.1 os.write()

sys.stdout.flush()
stdout_fd = sys.stdout.fileno()
os.write(stdout_fd, bytes_data)

2.2 sys.stdout.buffer.write()

sys.stdout.flush()
sys.stdout.buffer.write(bytes_data)

No comments:

Post a Comment