线程脚本不打印到控制台

Threading script not printing to console

真是百思不得其解,找不到答案

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()))

问题是这不打印。在终端中,我输入 python threading.py (这是文件名)并且没有错误输出。所以代码编译但它只是不打印。换句话说,这就是发生的事情:

$ python threading.py
$ 

我添加了 sys.stdout.flush() 以为需要重置标准输出,但无济于事。当我在任何函数的 while 循环之外添加一个随机打印语句,如 "hello world" 时,它就会被打印出来。此外,当我 运行 完全相同的代码在 ipython 时,它打印完美。这是从 YouTube 教程中复制的,不是我自己的代码。

关于它为什么不打印的任何想法? Python 我 运行ning 是 2.7.8。 提前致谢。

根据 thread 文档,

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.

因此很可能您的子线程在打印任何内容之前就被终止了,因为主线程结束得太快了。

快速的解决办法是让你的主线程在结束前等待;添加一个 time.sleep 方法作为最后一行。

您也可以使用 threading 代替 thread,并使用 Thread.join,这会强制主线程等待子线程完成执行。