Skip to main content
 首页 » 编程设计

Python什么都不打印

2025年05月04日10sharpest

只是按照一个教程,据我所知已经完全复制了它,但我的根本不会打印任何东西,它显然应该不断地从每个函数打印,但我似乎没有得到任何返回,不确定为什么 ?

#!/usr/bin/env python 
 
import thread 
import time 
import random 
 
def runOften(threadName, sleepTime): 
    while 1 < 2: 
        time.sleep(sleepTime) 
        print "%s" %(threadName) 
 
def runLessOften(threadName, sleepTime): 
    while 1 < 2: 
        time.sleep(sleepTime) 
        print "%s" %(threadName) 
 
def runRandomly(threadName, sleepTime): 
    while 1 < 2: 
        time.sleep(sleepTime) 
        print "%s" %(threadName) 
 
try: 
    thread.start_new_thread(runOften, ("Often Runs", 2)) 
    thread.start_new_thread(runLessOften, ("Less Often Runs!", 2)) 
    thread.start_new_thread(runRandomly, ("Fast and random", random.random())) 
 
except Exception, e: 
    print str(e)  

请您参考如下方法:

把它放在代码的末尾:

while True: 
    pass 

您的程序提前终止。

您的“MainThread”中没有任何内容。您产生了 3 个线程,但在所谓的“主程序”中什么都不做。所以 Python 正常终止。

将上面的内容添加到最后,我得到以下输出:

$ python foo.py 
Fast and random 
Fast and random 
Fast and random 
Often Runs 
 Less Often Runs! 
Fast and random 
Fast and random 
Fast and random 
^CTraceback (most recent call last): 
  File "foo.py", line 30, in <module> 
    while True: 
KeyboardInterrupt