Skip to main content
 首页 » 编程设计

python之python中打印函数的错误

2025年05月04日19leader

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 操作系统中都运行它。但 bug 出现在两者中。

请您参考如下方法:

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

将 flush=True 添加到 print() 调用以强制手动刷新:

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

stdout 是 commonly line-buffered when connected to a terminal , 否则 block 缓冲;线路缓冲在避免终端过于频繁的更新和及时向用户提供信息之间取得平衡。