我想创建一个可以计算的功能。倒数,我想访问计数值,每个让我们说另一个函数500毫秒。
我怎么能每隔500毫秒返回一个'a'这个值,所以我可以在每个例外情况下读取它。 500ms?
PS。我使用的是Python 2.7
到目前为止,这是我的代码,产量使用率却没有达到我的要求:
import time
class PLCApplication(object):
def generate_data(self):
a = 0
countup = True
while a >= 0:
time.sleep(0.5)
if countup == True:
a += 2
else:
a -= 2
if a < 0:
countup = True
a += 2
if a == 12:
countup = False
a -= 2
yield a
while True:
plc = PLCApplication()
b = plc.generate_data()
for z in b:
time.sleep(0.5)
print'z ...',z
编辑:
这是我想要实现的功能。感谢:
import time
from drawnow import *
import matplotlib.pyplot as plt
x = []
y = []
plt.ion()
class PLCApplication(object):
def generate_data(self):
a = 0
countup = True
while a >= 0:
time.sleep(0.5)
if countup: # no need to do test if it equals True
a += 2
else:
a -= 2
if a < 0:
countup = True
a += 2
if a == 12:
countup = False
a -= 2
yield a
def makefig(self):
plt.ylim(-10,30)
plt.plot(x, 'ro-', label='testgraph')
plt.grid(True)
if __name__ == '__main__':
plc = PLCApplication()
cnt = 0
for t in plc.generate_data():
i = t
x.append(int(i))
cnt=cnt+1
if cnt > 20:
x.pop(0)
print x, cnt
drawnow(plc.makefig)
答案 0 :(得分:1)
来自Python Coroutine page的示例似乎是以非阻塞的方式使用新的asyncio
。
import asyncio
import datetime
@asyncio.coroutine
def display_date(loop):
end_time = loop.time() + 5.0
while True:
print(datetime.datetime.now())
if (loop.time() + 1.0) >= end_time:
break
yield from asyncio.sleep(1)
loop = asyncio.get_event_loop()
# Blocking call which returns when the display_date() coroutine is done
loop.run_until_complete(display_date(loop))
loop.close()
答案 1 :(得分:1)
更新:根据C14L的评论更新答案,原始答案如下。
import time
class PLCApplication(object):
def generate_data(self):
a = 0
countup = True
while a >= 0:
time.sleep(0.5)
if countup: # no need to do test if it equals True
a += 2
else:
a -= 2
if a < 0:
countup = True
a += 2
if a == 12:
countup = False
a -= 2
yield a
def do_stuff(b):
print b
if __name__ == '__main__':
plc = PLCApplication()
for t in plc.generate_data():
do_stuff(t)
原始答案:
您需要在print a
循环内的适当位置while
:
[...]
while a >= 0:
print a
time.sleep(0.5)
[...]