我希望运行模拟当在同时在绘图中输出其进度。我一直在研究很多线程和多重处理的示例,但它们都非常复杂。所以我想用Python的新asyncio
图书馆这应该更容易。
我找到了一个例子(如何在异步函数中使用“yield”? https://stackoverflow.com/questions/37549846/how-to-use-yield-inside-async-function)并根据我的原因修改了它:
import matplotlib.pyplot as plt
import asyncio
import numpy as np
class DataAnalysis():
def __init__(self):
# asyncio so we can plot data and run simulation in parallel
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(self.plot_reward())
finally:
loop.run_until_complete(
loop.shutdown_asyncgens()) # see: https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.AbstractEventLoop.shutdown_asyncgens
loop.close()
async def async_generator(self):
for i in range(3):
await asyncio.sleep(.4)
yield i * i
async def plot_reward(self):
# Prepare the data
x = np.linspace(0, 10, 100)
# Plot the data
plt.plot(x, x, label='linear')
#plt.show()
# add lines to plot
async for i in self.async_generator():
print(i)
# Show the plot
plt.show()
if __name__ == '__main__':
DataAnalysis()
Question
我添加了一个简单的plt.show()
并且程序仍然冻结。我想与asyncio
我可以并行运行它吗?显然我的知识还很缺乏。
执行以下操作的示例将非常有帮助:
- 向绘图添加一条线(
matplotlib
) 每次async_generator
返回一个值。
首先,我误解了 asyncio,它不会并行运行(使用 asyncio 进行并行任务 https://stackoverflow.com/questions/40558484/use-asyncio-for-parallel-tasks).
似乎唯一对我有用的是plt.pause(0.001)
(使用 Matplotlib 以非阻塞方式绘图 https://stackoverflow.com/questions/28269157/plotting-in-a-non-blocking-way-with-matplotlib). plt.draw()
打开一个窗口,但没有显示任何内容plt.show
冻结程序。看起来plt.show(block=False)
已弃用并使用plt.ion
给出了程序结束时最终结果关闭的问题。还await asyncio.sleep(0.1)
并没有让剧情划出一条线。
工作代码
import matplotlib.pyplot as plt
import asyncio
import matplotlib.cbook
import warnings
warnings.filterwarnings("ignore",category=matplotlib.cbook.mplDeprecation)
class DataAnalysis():
def __init__(self):
# asyncio so we can plot data and run simulation in parallel
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(self.plot_reward())
finally:
loop.run_until_complete(
loop.shutdown_asyncgens()) # see: https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.AbstractEventLoop.shutdown_asyncgens
loop.close()
# keep plot window open
plt.show()
async def async_generator(self):
for i in range(3):
await asyncio.sleep(.4)
yield i * i
async def plot_reward(self):
#plt.ion() # enable interactive mode
# receive dicts with training results
async for i in self.async_generator():
print(i)
# update plot
if i == 0:
plt.plot([2, 3, 4])
elif i == 1:
plt.plot([3, 4, 5])
#plt.draw()
plt.pause(0.1)
#await asyncio.sleep(0.4)
if __name__ == '__main__':
da = DataAnalysis()
Notes
但是您会收到一条已弃用的消息:python3.6/site-packages/matplotlib/backend_bases.py:2445: MatplotlibDeprecationWarning: Using default event loop until function specific to this GUI is implemented
warnings.warn(str, mplDeprecation)
,您可以通过以下方式抑制:warnings.filterwarnings()
.
我不确定是否asyncio
对于我的用例来说实际上是必要的......
之间的区别threading
and multiprocessing
对于有兴趣的人:多处理 vs 线程 Python https://stackoverflow.com/questions/3044580/multiprocessing-vs-threading-python
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)