1
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.

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Why does buffering happen here?
@Jerence: because that's the default setting for stdin/stdout. It makes sense to wait for a newline character in the fast majority of use cases and it makes screen updates more efficient.
So in which situation does it happen? I run print(x, end='') many times, but this case never happens.
@Jerence: where are you running it? In the Python interpreter? And it matters if x contains a newline character of its own.
Yes, in the python interpreter. But in this case, string “<<<“ does not contain its own newline character.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.