gpt4 book ai didi

python - 如何使用 Python 在后台运行方法

转载 作者:太空宇宙 更新时间:2023-11-03 17:05:55 26 4
gpt4 key购买 nike

我正在尝试在 python 后台运行一个方法(一个通过来自 aws 服务器的消息不断更新的类),并且我使用它作为模板。问题是,我无法打印('检查点')或打印('再见')。它只是继续运行 run(self)。这是为什么?

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

最佳答案

我已经运行了你的代码,它工作正常(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
...

关于python - 如何使用 Python 在后台运行方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34605005/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com