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

时间:2018-10-31 23:57:53

标签: python python-3.x multithreading networking

我有一个正在处理的项目,但已在下面的小示例代码中提出了问题。我首先创建一个套接字,然后生成一个线程以接受连接(这样我可以有多个客户端连接)。收到连接后,我将生成另一个线程,该线程将在该连接上进行侦听。我也在一个循环中,提示我可以在其中输入任何内容,然后它将其打印回给我。

问题出在我通过插座收到东西时。它将打印到屏幕上。但是,当我尝试在控制台中键入任何内容时,控制台上来自套接字的文本将被删除。我想保留套接字中的所有内容以保留在屏幕上。

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.

1 个答案:

答案 0 :(得分:1)

主题行中有关您问题的答案(关于sys.stdout的缓冲,默认为print写入):每个线程都与同一个sys.stdout对象通信,它通常只有一个缓冲区,不过当然您可以根据需要更改sys.stdout,并且可以向file=whatever提供print()自变量。

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

  

但是当我尝试在控制台中键入任何内容时,控制台上来自套接字的文本将被删除。我想保留套接字中的所有内容以保留在屏幕上。

Python的输入阅读器默认通过readline库。有多个具有不同行为的不同的readline库,但是其中大多数提供输入历史记录,行编辑和其他精美功能。他们倾向于通过在终端窗口中四处移动光标来实现这些花哨的功能(假设您首先使用的是某种终端窗口),并使用“清除行尾”操作次。这些操作通常会干扰,覆盖或擦除在这些奇特的技巧之前,之中和/或之后发生的其他输出。

具体的细节因操作系统,终端仿真器以及Python使用的readline库而异。