这真的让我感到困惑,我找不到答案。
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(),以为需要重置stdout,但是没有效果。当我在任何一个函数的while循环之外添加一个随机的print语句,比如"hello world",它会被打印出来。而且,当我在ipython中运行完全相同的代码时,它可以完美地打印出来。这段代码是从YouTube教程中复制来的,不是我的代码。
有什么想法为什么它没有打印?我使用的Python版本是2.7.8。 提前感谢您的帮助。