【发布时间】:2010-08-12 17:11:09
【问题描述】:
我显然误解了 Python Thread 对象的 daemon 属性的基本原理。
考虑以下几点:
daemonic.py
import sys, threading, time
class TestThread(threading.Thread):
def __init__(self, daemon):
threading.Thread.__init__(self)
self.daemon = daemon
def run(self):
x = 0
while 1:
if self.daemon:
print "Daemon :: %s" % x
else:
print "Non-Daemon :: %s" % x
x += 1
time.sleep(1)
if __name__ == "__main__":
print "__main__ start"
if sys.argv[1] == "daemonic":
thread = TestThread(True)
else:
thread = TestThread(False)
thread.start()
time.sleep(5)
print "__main__ stop"
来自 python 文档:
整个 Python 程序在什么时候退出 没有存活的非守护线程。
因此,如果我将 TestThread 作为守护程序运行,我希望它在主线程完成后退出。但这不会发生:
> python daemonic.py daemonic
__main__ start
Daemon :: 0
Daemon :: 1
Daemon :: 2
Daemon :: 3
Daemon :: 4
__main__ stop
Daemon :: 5
Daemon :: 6
^C
我没有得到什么?
正如 Justin 和 Brent 所猜测的那样,我使用的是 Python 2.5。刚回到家并在我自己的运行 2.7 的机器上试用,一切正常。感谢您的帮助!
【问题讨论】:
标签: python