我正在尝试在python的后台运行一个方法(一个不断更新来自aws服务器的消息的类),我正在使用它作为模板。问题是,我无法打印('检查点')或打印('再见')。它只是继续运行(自我)。这是为什么?
import threading
import time
class ThreadingExample(object):
""" Threading example class
The run() method will be started and it will run in the background
until the application exits.
"""
def __init__(self, interval=1):
""" Constructor
:type interval: int
:param interval: Check interval, in seconds
"""
self.interval = interval
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
def run(self):
""" Method that runs forever """
while True:
# Do something
print('Doing something imporant in the background')
time.sleep(self.interval)
example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
编辑:我忘了提到我在Ubuntu 14.04 LTS 64位上使用Python 2.7.6
答案 0 :(得分:1)
我运行你的代码它运行正常(python34,ubuntu14)
with thread.daemon = True:
Doing something important in the background
Doing something important in the background
Doing something important in the background
Checkpoint
Doing something important in the background
Doing something important in the background
Bye
守护程序= False:
Doing something imporant in the background
Doing something important in the background
Doing something important in the background
Checkpoint
Doing something important in the background
Doing something important in the background
Bye
Doing something important in the background
Doing something important in the background
Doing something important in the background
Doing something important in the background
...
答案 1 :(得分:0)
从来没有我固定它
而不是
thread = threading.Thread(target=self.run, args=())
我有
thread = threading.Thread(target=self.run(), args=())
我不知道为什么,但这些括号使它永远运行