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

2024-04-20 12:33:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个项目,我正在工作,但我已经提出了一个小样本代码下面的问题。我首先创建一个套接字,然后生成一个线程来接受连接(这样我可以让多个客户端连接)。当我收到一个连接时,我会产生另一个线程来监听这个连接。我也在一个循环中,它给我一个提示,我可以输入任何东西,它会把它打印出来给我。在

当我通过套接字接收到某些内容时,问题就在于此。它会打印到屏幕上。但是当我试图在控制台中键入任何内容时,控制台上来自套接字的文本将被删除。我想把插座上的一切都保留在屏幕上。在

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() 

这里可以找到它正在做什么的图片:https://imgur.com/a/hCWznfE

I started the server and typed in the prompt (cmd>). It takes my input and prints it back to me.

Now I used netcat and connected to the server. The server shows that a client was connected.

I use netcat to send messages to the server, and the server displays.

I go back to the server and start to type and the strings from the client are removed and I am back at the prompt.


Tags: importtruedataportdefsocketconnthread
1条回答
网友
1楼 · 发布于 2024-04-20 12:33:41

您在主题行中的问题(关于sys.stdout的缓冲,默认情况下print写入)的答案基本上是否定的:每个线程都与同一个sys.stdout对象对话,该对象通常只有一个缓冲区,当然,如果您愿意,您可以修改sys.stdout,并且可以为print()提供{}参数。在

然而,这一特定部分是可以解释的:

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的输入读取器通过readline库。有多个不同的readline库,它们的行为各不相同,但大多数提供了输入历史、行编辑和其他奇特的功能。他们倾向于通过在终端窗口中移动光标来实现这些奇特的功能,假设您首先使用某种终端窗口,并且有时使用“清除到行尾”操作。这些操作通常会干扰、覆盖或删除在这些花招之前、期间和/或之后发生的其他输出。在

精确的细节会有很大的不同,这取决于您的操作系统、终端仿真器以及Python使用的readline库。在

相关问题 更多 >