2

I want to create a python script that prints out messages from one thread, while still waiting for you to input on another. Is this possible? And if so, how?

System: Windows 7

Language: Python 2.7

I have tried this (modified from a different question):

import threading
import time

def message_loop():
    while True:
        time.sleep(1)
        print "Hello World"

thread = threading.Thread(target = message_loop)
thread.start()

while True:
    input = raw_input("Prompt> ")

But what happens is: the program waits until I have finished inputting before it outputs Hello World.

2
  • Adding to Coffee's question, what have you read? Did you look at the Python documentation? Commented Jul 27, 2013 at 4:16
  • I have read the documentation, and I have tried code done by others, but what happens is the code whats for me to press enter and then it outputs Commented Jul 27, 2013 at 4:29

2 Answers 2

2

It's absolutely possible. If you have a function that prints output (let's call it print_output) you can start it up in a different thread using the threading module:

>>> import threading
>>> my_thread = threading.Thread(target=print_output)
>>> my_thread.start()

You should now start getting your output. You can then run the input bit on the main thread. You could also run it in a new thread, but there are some advantages to running input in the main thread.

Sign up to request clarification or add additional context in comments.

2 Comments

That just tells me how to thread, it doesn't do what I want it to though
@Pyro: I can't reproduce your problem. It works fine for me, although I'm on 2.6 rather than 2.7 and I'm not on Windows.
2

This works for me. The code prints message before you input 'q'

import threading
import time


def run_thread():
    while True:
        print('thread running')
        time.sleep(2)
        global stop_threads
        if stop_threads:
            break


stop_threads = False
t1 = threading.Thread(target=run_thread)
t1.start()
time.sleep(0.5)

q = ''
while q != 'q':
    q = input()

stop_threads = True
t1.join()
print('finish')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.