Loading

python捕获stdout生成动画

项目希望runtime可视化某个中间变量,核心思想如下:
输出log经由stdout输入python并构造animation完成可视化。

"""
=====
Decay
=====

This example showcases:

- using a generator to drive an animation,
- changing axes limits during an animation.
"""
SCRIPT="n=0;while true;do echo $n,$n;n=$((n+1));done"
import subprocess
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

def data_gen():
    cmd = subprocess.Popen(SCRIPT, shell=True, stdout=subprocess.PIPE)
    for line in cmd.stdout:
        yield eval(line.decode().strip()) # remove prefix b' and \n

def init():
    ax.set_ylim(-1.1, 1.1)
    ax.set_xlim(0, 100)
    del xdata[:]
    del ydata[:]
    line.set_data(xdata, ydata)
    # return line,

plt.style.use('dark_background')
fig, ax = plt.subplots()
line, = ax.plot([], [], lw=2, color='lime')
xdata, ydata = [], []


def run(data):
    # update the data
    t, y = data
    xdata.append(t)
    ydata.append(np.sin(2*np.pi*y/10) * np.exp(-y/100.))
    xmin, xmax = ax.get_xlim()

    if t >= xmax:
        ax.set_xlim(xmin, 2*xmax)
        ax.figure.canvas.draw()
    line.set_data(xdata, ydata)

    # return line,

ani = animation.FuncAnimation(fig, run, data_gen, interval=50, init_func=init) # 50ms = 20fps
plt.show()

matplotlib.animation.FuncAnimation — Matplotlib 3.5.0 documentation

posted @ 2022-04-23 18:14  azureology  阅读(55)  评论(0)    收藏  举报