Python Threading and Input

2.3k Views Asked by At

I am new to Python threading and I need some help with some code, I am working on making an IRC client as a hobby but I need the ability for the user to be able to input text and also pull messages from the IRC server, etc.

In this example, whilst getting user input, the .'s are being outputted after the text that the user has entered I would like the input to be separate to what is being outputted in the listen function.

import threading
import time
import sys


def listen():
    sys.stdout.write("Listening...")
    sys.stdout.flush()
    for i in range(5):
        time.sleep(1)
        sys.stdout.write(".")
        sys.stdout.flush()
    return

def test_input():
    input("Here: ")
    return

threads = []
listen_thread = threading.Thread(target=listen)
threads.append(listen_thread)
listen_thread.start()

input_thread = threading.Thread(target=test_input)
threads.append(input_thread)
input_thread.start()

Currently, if I type 'hello there how are you' I get: Listening...Here: .hell.o there. how ar.e you.

I would like Listening........ Here: hello there how are you with the .'s after the 'Listening'

(Sorry about the wording)

1

There are 1 best solutions below

2
On

You immediately start the test_input() thread after starting the listen() thread. And because the test_input() thread runs in parallel you immediately print "Here".
You should call a.start() only after having printed all the dots. (which takes 5 seconds).

Also try to use more descriptive variable names.