首页 > 解决方案 > 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()

recv()被调用时,print('<<<', end='') 不打印出来。有没有人知道背后的原因?顺便说一句,我在 Pycharm IDE 和 Linux OS 中都运行它。但是错误出现在两者中。

标签: pythonpython-3.xprintingbufferingoutput-buffering

解决方案


不,这不是错误。您的stdout流是行缓冲\n的,并且在打印换行符之前不会自动刷新。数据已写入缓冲区,但在刷新缓冲区之前不会写入屏幕。

添加flush=Trueprint()调用以强制手动刷新:

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

stdout连接到终端时通常是行缓冲的,否则是块缓冲的;行缓冲在避免终端过于频繁的更新和及时向用户获取信息之间取得平衡。


推荐阅读