Python打印没什么?

时间:2014-05-21 07:10:35

标签: python multithreading printing

只是按照教程进行操作并据我所知将其复制完全然而我的根本没有打印任何内容,显然应该从每个功能中不断打印但我似乎没有得到任何东西回来,不知道为什么?

#!/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) 

3 个答案:

答案 0 :(得分:6)

将其放在代码的末尾:

while True:
    pass

您的程序过早终止。

您的&#34; MainThread&#34;中没有任何内容。你产生3个线程,但在所谓的&#34;主程序&#34;中什么都不做。所以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

答案 1 :(得分:4)

更好的解决方案是使用threading模块,该模块提供Thread类 - 面向对象的线程接口。

这样,我们可以轻松join()三个正在运行的线程(等待它们完成)。

调整您的示例:

import threading
import time
import random

keep_running = True

def runOften(threadName, sleepTime):
    while keep_running:
        time.sleep(sleepTime)
        print "%s" %(threadName)

def runLessOften(threadName, sleepTime):
    while keep_running:
        time.sleep(sleepTime)
        print "%s" %(threadName)

def runRandomly(threadName, sleepTime):
    while keep_running:
        time.sleep(sleepTime)
        print "%s" %(threadName)


def main():
    global keep_running

    # Create the threads
    threads = []
    threads.append(threading.Thread(target=runOften, args=("Often Runs", 2)))
    threads.append(threading.Thread(target=runLessOften, args=("Less Often Runs!", 2)))
    threads.append(threading.Thread(target=runRandomly, args=("Fast and random", random.random())))

    # Start the threads
    for t in threads:
        t.start()

    # Wait for all of the threads to finish.
    # Note: KeyboardInterrupt will not be raised inside of a call to join()
    #       with no timeout. So we set an arbitrarily large timeout, which
    #       (for whatever reason) allows KeyboardInterrupt to be raised.
    while threads:
        for t in list(threads):          # Iterate over a copy
            try:
                t.join(1000)             # Arbitrary timeout value
                if not t.isAlive():      # If thread finished (join didn't time-out),
                    threads.remove(t)    # We'll no longer join() on it
            except KeyboardInterrupt:    # If we get a Ctrl+C,
                keep_running = False     # Set global flag, telling threads to stop looping

if __name__ == '__main__':
    main()

为什么这个更好而不是(尽管它在美学上不如)while True: pass?因为这将使CPU 忙等待为Ctrl + C,从而抢夺其他线程的宝贵执行时间。此解决方案将允许其他线程运行,仅在按下Ctrl + C时唤醒。

有关使用线程处理Ctrl + C的其他问题:

我还应该指出runRandomly并不像它的名字所暗示的那样;相反,它将始终在每次迭代中睡眠相同的时间。当程序开始时,该数量是随机决定的。

答案 2 :(得分:0)

我将在这里介绍OP使用circuits应用程序框架提供的代码行为的不同实现,因为:

  • 很优雅
  • 工作
  • 终止于^C
  • 它不使用线程
  • 它说明了相同的行为。

这个程序的行为基本上都与计时器和事件有关。

运行它会产生:

$ python foo.py 
Run Less Often
Run Often
Run Randomly
Run Less Often
Run Less Often
Run Often

代码:http://codepad.org/cV7HpHpv

#!/usr/bin/env python


from random import randint


from circuits import Component, Event, Timer


class App(Component):

    def init(self):
        Timer(5, Event.create("run_often"), persist=True).register(self)
        Timer(3, Event.create("run_less_often"), persist=True).register(self)
        Timer(randint(1, 10), Event.create("run_randomly")).register(self)

    def run_often(self):
        print "Run Often"

    def run_less_often(self):
        print "Run Less Often"

    def run_randomly(self):
        print "Run Randomly"

        Timer(randint(1, 10), Event.create("run_randomly")).register(self)


App().run()