Python 函数作为后台进程运行 [英] Python functions run as background processes

查看:87
本文介绍了Python 函数作为后台进程运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有一些方法可以让程序等待函数完成,但是有没有一种方法可以让函数在调用后在程序后台继续运行.

I know there are ways of making a program wait for a function to finish, but is there a way to make the function, once called, to carry on in the background of a program.

如果您正在制作程序计时器,这可能特别有用,如下所示.

This might be especially useful if you were making a program timer, like the one below.

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 中进行后台进程.

I hope there is a way to do background processes in python.

推荐答案

这听起来像线程.

线程模块相对简单,但要注意以这种方式执行任何与 CPU 相关的活动.有很多计时器和睡眠,或者 IO 绑定,那么这很好.

The threading module is relatively simple, but beware doing any CPU bound activities that way. With lots of timers and sleeps, or IO bound then this is fine.

线程模块示例:

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,您可能需要查看该模块.

To Clarify - relatively simple compared with the multiprocessing module - which you may want to look at if your background activity is CPU heavy.

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

The python docs have a good tutorial on this at: https://docs.python.org/2/library/threading.html#thread-objects

这篇关于Python 函数作为后台进程运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆