python中打印函数的一个bug? 从套接字导入* 从线程导入线程 udp_套接字=无 目的地ip=“” dest_端口=0 def send(): 尽管如此: content=输入(“[%s%d]%s%”(ip、端口、content.decode()) 打印(“
不,这不是错误。您的python中打印函数的一个bug? 从套接字导入* 从线程导入线程 udp_套接字=无 目的地ip=“” dest_端口=0 def send(): 尽管如此: content=输入(“[%s%d]%s%”(ip、端口、content.decode()) 打印(“,python,python-3.x,printing,buffering,output-buffering,Python,Python 3.x,Printing,Buffering,Output Buffering,不,这不是错误。您的stdout流是行缓冲的,在打印\n换行符之前不会自动刷新。数据已写入缓冲区,但在刷新缓冲区之前不会写入屏幕 将flush=True添加到print()调用以强制手动刷新: from socket import * from threading import Thread udp_socket = None dest_ip = '' dest_port = 0 def send(): while True: content = input('&l
stdout
流是行缓冲的,在打印\n
换行符之前不会自动刷新。数据已写入缓冲区,但在刷新缓冲区之前不会写入屏幕
将flush=True
添加到print()
调用以强制手动刷新:
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()
print(“不,这不是错误。您的stdout
流是行缓冲的,在打印\n
换行符之前不会自动刷新。数据已写入缓冲区,但在刷新缓冲区之前不会写入屏幕
将flush=True
添加到print()
调用以强制手动刷新:
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()
print('为什么会在这里发生缓冲?@Jerence:因为这是stdin/stdout的默认设置。在大多数快速的用例中,等待换行符是有意义的,它可以提高屏幕更新的效率。那么在哪种情况下会发生缓冲呢?我运行print(x,end='')很多次,但这种情况从未发生过。@Jerence:你在哪里运行它?在Python解释器中?如果x
包含自己的换行符,这很重要。是的,在Python解释器中。但是在这种情况下,字符串“为什么这里会发生缓冲?@Jerence:因为这是stdin/stdout的默认设置。在大多数快速的用例中,等待换行符是有意义的,它可以提高屏幕更新的效率。那么在哪种情况下会发生缓冲呢?我运行print(x,end=”)很多次,但这种情况从未发生过。@Jerence:你在哪里运行它?在Python解释器中?如果x
包含自己的换行符,这很重要。是的,在Python解释器中。但是在这种情况下,字符串