python - 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 中都运行它。但是错误出现在两者中。
解决方案
不,这不是错误。您的stdout
流是行缓冲\n
的,并且在打印换行符之前不会自动刷新。数据已写入缓冲区,但在刷新缓冲区之前不会写入屏幕。
添加flush=True
到print()
调用以强制手动刷新:
print('<<<', end='', flush=True)
stdout
连接到终端时通常是行缓冲的,否则是块缓冲的;行缓冲在避免终端过于频繁的更新和及时向用户获取信息之间取得平衡。
推荐阅读
- php - CodeIgniter 一查询多语句
- reactjs - 反应将图像添加到现有地图
- javascript - 如何动态创建以下 htm 代码
- django-rest-framework - 使用序列化程序(drf)在 django 中进行密码加密
- linux - 启动审计守护程序时出错
- android - 如何使用 python 和 kivy 启动器在 android 上备份/复制 .db 文件
- typescript - 为什么函数本身在 TypeScript 中评估为 true?
- c# - 将项目转换为 nuget 包
- mysql - 使用时间戳字段按天分组
- google-cloud-platform - 使用 --time_partitioning_field 查询流数据