Jer*_*nce 1 python printing buffering output-buffering python-3.x
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()
Run Code Online (Sandbox Code Playgroud)
当recv()被调用时,print('<<<', end='')
不打印出来.有没有人知道背后的原因?顺便说一下,我在Pycharm IDE和Linux OS中运行它.但是这两个问题都出现了.
不,那不是错误.您的stdout流是行缓冲的,\n在打印换行符之前不会自动刷新.数据已写入缓冲区,但在刷新缓冲区之前不会写入屏幕.
加入flush=True到print()呼叫强制手动冲洗:
print('<<<', end='', flush=True)
Run Code Online (Sandbox Code Playgroud)
stdout当连接到终端时,它通常是行缓冲的,否则是块缓冲的; 线路缓冲在避免过于频繁的终端更新和及时向用户获取信息之间取得平衡.
| 归档时间: |
|
| 查看次数: |
166 次 |
| 最近记录: |