简体   繁体   English

Python 线程是否打印到与主线程不同的缓冲区?

[英]Do Python threads print to a different buffer than the main thread?

I have a project I am working on but I have brought out the problem into a small sample code below.我有一个正在处理的项目,但我已将问题带入下面的一个小示例代码中。 I first create a socket and then spawn a thread to accept connections (so I can have multiple clients connect).我首先创建一个套接字,然后生成一个线程来接受连接(这样我就可以有多个客户端连接)。 When I receive a connection, I then spawn another thread that will listen on that connection.当我收到一个连接时,我会生成另一个线程来侦听该连接。 I am also in a loop that gives me a prompt where I can enter anything, and it will print it back out to me.我也在一个循环中,它给了我一个提示,我可以在其中输入任何内容,它会将它打印回给我。

The issue lies when I recieve something through the socket.问题在于当我通过套接字接收某些东西时。 It will print to the screen.它将打印到屏幕上。 But when I try to type anything in the console, the text that is on my console that came from the socket gets removed.但是,当我尝试在控制台中键入任何内容时,控制台上来自套接字的文本将被删除。 I want to keep everything from the socket to remain on the screen.我想保留套接字中的所有内容以保留在屏幕上。

import sys
import socket
from _thread import *

def recv_data(conn):
    while True:
        data = conn.recv(256)
        print(data)

def accept_clients(sock):
    while True:
        conn, addr = sock.accept()
        print("\nConnected with %s:%s\n" % (addr[0], str(addr[1])))
        start_new_thread(recv_data, (conn,))

def start_socket(ip, port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print("Socket created")

    try:
        port = int(port)
    except ValueError:
        print("Invalid port number.")
        return

    try:
        sock.bind((ip, int(port)))
    except socket.error as msg:
        print("Bind failed. Error Code : %s" % (msg))
        return

    print("Socket bind complete")
    sock.listen(5)
    print("Socket now listening")

    start_new_thread(accept_clients, (sock,))

def get_input():
    while True:
        data = input("cmd> ")
        print(data)


start_socket('localhost', 5555) 
get_input() 

Pictures can be found here of what it is doing: https://imgur.com/a/hCWznfE可以在这里找到它正在做什么的图片: https : //imgur.com/a/hCWznfE

我启动了服务器并输入了提示符 (cmd>)。它接受我的输入并将其打印回给我。

现在我使用netcat并连接到服务器。服务器显示客户端已连接。

我使用netcat向服务器发送消息,服务器显示。

我回到服务器并开始输入,然后删除了来自客户端的字符串,然后我又回到了提示符处。

The answer to your question in the subject line (about buffering for sys.stdout , to which print writes by default) is essentially no: each thread talks to the same sys.stdout object, which just has one buffer in general, though of course you can alter sys.stdout if you like, and you can supply file=whatever arguments to print() .您在主题行中的问题的答案(关于sys.stdout缓冲,默认情况下print写入)基本上是否定的:每个线程都与同一个sys.stdout对象对话,尽管当然,它通常只有一个缓冲区如果您愿意,您可以更改sys.stdout ,并且您可以向print()提供file=whatever参数。

This specific part, however, is explainable:然而,这一特定部分是可以解释的:

But when I try to type anything in the console, the text that is on my console that came from the socket gets removed.但是,当我尝试在控制台中键入任何内容时,控制台上来自套接字的文本将被删除。 I want to keep everything from the socket to remain on the screen.我想保留套接字中的所有内容以保留在屏幕上。

Python's input reader goes through a readline library by default.默认情况下,Python 的输入阅读器通过一个readline库。 There are multiple different readline libraries with varying behavior, but most of them provide input history, line editing, and other fancy features.有多个不同的 readline 库具有不同的行为,但大多数都提供输入历史、行编辑和其他奇特的功能。 They tend to implement these fancy features by moving the cursor around in your terminal window—assuming you're using some kind of terminal window in the first place—and using "clear to end of line" operations at times.他们倾向于通过在终端窗口中移动光标来实现这些奇特的功能——假设你首先使用某种终端窗口——并且有时使用“清除到行尾”操作。 These operations will often interfere with, and overwrite or erase, other output that occurs before, during, and/or after these fancy tricks.这些操作通常会干扰、覆盖或擦除在这些花哨的技巧之前、期间和/或之后发生的其他输出。

The precise details vary, quite a lot, based on your OS, terminal emulator, and which readline library your Python is using.根据您的操作系统、终端模拟器以及您的 Python 使用的 readline 库,确切的细节会有很大差异。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 python-为什么在所有线程加入之前主线程打印结束行 - python - Why main thread print ended line before all threads join 在主线程以外的其他线程中未提供自动堆栈跟踪 - Automatic Stack Trace not being given in threads other than the main thread Python子进程:如何使用与主线程不同的解释器运行python脚本 - Python subprocess: How to run a python script using a different intepreter than the main thread 用于播放不同声音的音频的python线程,似乎没有正确锁定,并且在线程调用之后函数的开始返回 - python threads for audio playing different sounds, do not seem to be locking correctly, and beginning of function returned to after thread calls 如何在Python中退出主线程并使子线程在后台继续 - How to exit main thread in Python and make the child threads continue in background 如何从Python中的主线程终止Producer-Consumer线程? - How to terminate Producer-Consumer threads from main thread in Python? 主线程中对queue.join()的调用对非主线程有什么影响? - What does a call on queue.join() in main thread do to non-main threads? Python线程名称是否反映了开放线程的数量? - Do Python thread names reflect the number of open threads? 如何使一个线程等待其他线程在python中执行特定任务 - How to make a thread wait for other threads to do a specific task in python 带有os.system()调用的Python线程。 主线程不在ctrl + c上退出 - Python threads with os.system() calls. Main thread doesn't exit on ctrl+c
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM