由于问题有点宽泛,我必须假定一两件事情。 例如,你没有说明你打算如何提供事件来处理机器。
我应该实现一个循环还是有其他的方式来做到这一点?
那么,这取决于你打算使用什么样的事件机制。有些实现会为做,其他人不会。
你可以将一台机器连接到一个事件队列,你必须自己处理事件循环。在下面的例子中,我将随机数字提供给一个模型,该模型将根据传递的数字使用机器来更改状态。
from transitions import Machine
from threading import Thread
import random
import time
try:
from Queue import Queue
except ImportError: # Module has been renamed in Python 3
from queue import Queue
class Model(Thread):
def __init__(self, event_queue):
self.event_queue = event_queue
# has to be called whenever something inherits from Thread
super(Model, self).__init__()
def run(self):
while True:
event = self.event_queue.get(block=True)
# 0 will end the event loop
if event == 0:
return
# if the passed number is even, switch to Even state
elif event % 2 == 0:
self.even()
# switch to Odd state otherwise
else:
self.odd()
states = ['Even', 'Odd']
transitions = [['even', '*', 'Even'],
['odd', '*', 'Odd']]
event_queue = Queue()
model = Model(event_queue)
machine = Machine(model, states=states, transitions=transitions, initial='Even')
model.start()
for n in random.sample(range(1, 20), 5):
event_queue.put(n)
time.sleep(0.1)
print("Number {0} was passed to the model which is now in state {1}".format(n, model.state))
# shut down model thread
event_queue.put(0)
该模型实际上会块直到它收到下一个事件,将关闭它接收到的事件0
的时刻。
大家好while循环,我忘了,我使用python转换模块quesiton提。 https://github.com/pytransitions/transitions –
你提供的不是Python工作的代码......除了你可能想看'while'循环与'threading'配对 – gionni