Threading script not printing to console

13.4k views Asked by At

this is really baffling me, and I cannot find the answer.

import thread
import time
import random
import sys 

sys.stdout.flush()

def run_often(thread_name, sleep_time):
    while True:
        time.sleep(sleep_time)
        print "%s" % (thread_name)
def run_randomly(thread_name, sleep_time):
    while True:
        time.sleep(sleep_time)
        print "%s" % (thread_name)

thread.start_new_thread(run_often,("Often runs", 2)) 
thread.start_new_thread(run_randomly, ("Fast and random", random.random()))

the problem is that this does not print. In the terminal, I type python threading.py (that's the file name) and no error is output. So the code compiles but it just does not print. In other words, this is what happens:

$ python threading.py
$ 

I added sys.stdout.flush() thinking that stdout needed to be reset, but to no avail. And when I add a random print statement like "hello world" outside of the while loop in any of the functions, it gets printed. Also, when I run the exact same code in ipython, it prints perfectly. This was copied from a YouTube tutorial, and is not my own code.

Any ideas as to why it's not printing? The Python I'm running is 2.7.8. Thanks in advance.

1

There are 1 answers

2
Kevin On BEST ANSWER

According to the thread documentation,

When the main thread exits, it is system defined whether the other threads survive. On SGI IRIX using the native thread implementation, they survive. On most other systems, they are killed without executing try ... finally clauses or executing object destructors.

So it is most likely that your child threads are being terminated before they can print anything, because the main thread ends too quickly.

The quick solution is to make your main thread wait before ending; add a time.sleep method as the last line.

You could also use threading instead of thread, and use Thread.join, which forces the main thread to wait until the child thread is finished executing.