python - python中打印函数的错误?

标签 python python-3.x printing buffering output-buffering

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)

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

关于python - python中打印函数的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51458170/

相关文章:

java - 在双面模式下使用 Java 打印横向文档

python - 你能在 Django 中执行多线程任务吗?

python - OpenCV 错误 : (-215) scn == 3 || scn == 4 in function ipp_cvtColor

python - 重写函数以递归方式执行(python)

python-3.x - Lookup Pandas Dataframe 比较不同大小的数据框

Eclipse - 使用不同的颜色进行打印

python - 尝试运行 Flask Web 应用程序时出现 null is not defined 错误

python linux Selenium : chrome not reachable

python - 带有 pyautogui 的 .pyx 脚本可以在spyder/cmd中运行,但不能在bat文件中运行

css - 是否可以打印您网页上显示的 YouTube 视频静态截图?