Python 函数作为后台进程运行

2024-06-28

我知道有很多方法可以让程序等待函数完成,但是有没有办法让函数一旦被调用,就在程序的后台继续执行。

如果您正在制作一个程序计时器(如下所示),这可能特别有用。

import time
count = 0    
def timer():
    while True():
        time.sleep(60)
        count += 1            
        print("This program has now been running for " + str(count) + " minutes"
timer() # Carry this function out in the background
print("Hello! Welcome to the program timer!")
name = raw_input("What is your name?")
print("Nice to meet you, " + name + "!")
# More stuff here...

我希望有一种方法可以在 python 中进行后台进程。


这听起来像线程。

线程模块相对简单,但要小心以这种方式执行任何 CPU 密集型活动。如果有大量的定时器和睡眠,或者 IO 限制,那就没问题了。

线程模块示例:

import time
from threading import Thread

def timer(name):
    count = 0
    while True:
        time.sleep(60)
        count += 1            
        print("Hi " + name + "This program has now been running for " + str(count) + " minutes.")

print("Hello! Welcome to the program timer!")
name = raw_input("What is your name?")
print("Nice to meet you, " + name + "!")
background_thread = Thread(target=timer, args=(name,))
background_thread.start()

澄清一下 - 与多处理模块相比相对简单 - 如果您的后台活动占用大量 CPU,您可能需要查看该模块。

python 文档对此有一个很好的教程:https://docs.python.org/2/library/threading.html#thread-objects https://docs.python.org/2/library/threading.html#thread-objects

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python 函数作为后台进程运行 的相关文章

随机推荐