Search code examples
pythonpython-3.xprintingbufferingoutput-buffering

A bug of print function in python?


from socket import *
from threading import Thread

udp_socket = None
dest_ip = ''
dest_port = 0


def send():
    while True:
        content = input('<<<')
        udp_socket.sendto(content.encode(), (dest_ip, dest_port))


def recv():
    while True:
        data = udp_socket.recvfrom(1024)
        content, address = data
        ip, port = address
        print('\r>>>[%s %d] %s' % (ip, port, content.decode()))
        print('<<<', end='')


def main():
    global udp_socket, dest_ip, dest_port
    udp_socket = socket(AF_INET, SOCK_DGRAM)
    udp_socket.bind(('', 7788))

    dest_ip = input('Please enter the IP: ')
    dest_port = int(input('Please enter the port: '))

    ts = Thread(target=send)
    tr = Thread(target=recv)
    ts.start()
    tr.start()


if __name__ == '__main__':
    main()

When recv() is called, print('<<<', end='') is not printed out. Is there anybody who knows the reason behind it? By the way, I run it in both of Pycharm IDE and Linux OS. But the bug appears in both.


Solution

  • No, that's not a bug. Your stdout stream is line buffered and will not be auto-flushed until a \n newline is printed. The data has been written to the buffer, but won't be written to your screen until the buffer is flushed.

    Add flush=True to the print() call to force a manual flush:

    print('<<<', end='', flush=True)
    

    stdout is commonly line-buffered when connected to a terminal, block-buffered otherwise; line-buffering strikes a balance between avoiding too-frequent updates of the terminal and getting information to the user in a timely manner.