简体   繁体   中英

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

我启动了服务器并输入了提示符 (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() .

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. There are multiple different readline libraries with varying behavior, but most of them provide input history, line editing, and other fancy features. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM