[英]Running a Python function as a background process
我编写了以下代码,这些代码根据time.sleep中的值进行更新。
import time
class Mine:
def __init__(self, stock):
self.stock = 0
while True:
self.stock += 1
print(self.stock)
time.sleep(1)
bigmine = Mine(0)
如您所见,对于循环的每个滴答声,我都希望有一个动作发生。 问题是,正如预期的那样,此循环重复执行时,代码没有其他任何运行。
如何进行后台处理,以便随后可以运行其他命令来重置库存或显示矿山的库存?
使用多线程这一概念可以实现以下目的:
import threading
from threading import Thread
def __init__(self, stock):
self.stock = 0
while True:
self.stock += 1
print(self.stock)
time.sleep(1)
def func2():
print 'Foreground code Here!'
if __name__ == '__main__':
Thread(target = func1).start()
Thread(target = func2).start()
欲了解更多信息,请点击这里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.