【问题标题】:Running two python files at once一次运行两个 python 文件
【发布时间】:2021-02-27 16:37:45
【问题描述】:

我有两个 python 文件,一个在 pygame 中运行模拟,另一个获取数据并绘制图表。我希望它们在两个单独的窗口中运行,但我希望在模拟运行时记录数据。我尝试过多线程,但它似乎不起作用。

这两个函数都是 while 真正的循环,我希望它们并行运行。

def main():
    while True:
        clock.tick(simSpeed)

        # quit function
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        pendulum.update()
        drawWindow(screen, pendulum)

threading.Thread(target=main).start()
threading.Thread(target=graphData).start()
def graphData():
    while True:
        x = data.data["x"]
        y = data.data["y"]
        plot1 = plt.figure(1)
        plt.title("poopyhead")
        plt.plot(y, x)

        plot2 = plt.figure(5)
        plt.plot(x, y)

        plot1.clear()
        plot2.clear()

        plt.show()
        time.sleep(1)

【问题讨论】:

  • 多线程时遇到什么错误?
  • 当我使用多线程时,第一个函数只运行而第二个函数不运行。我认为这是因为没有时间等待某事发生(例如等待接收数据或某事)。但是我的主循环运行了,而图形数据根本没有运行。
  • 不确定,但尝试将 clock.tick(simSpeed) 更改为 time.sleep(seconds)。为此,您需要导入时间。它是内置的。
  • 这不是一个坏主意。我的问题是游戏将不再以恒定速度运行。 clock.tick() 让它以恒定的 fps 运行,并使每个 while 循环花费相同的时间。据我所知,time.sleep 不会那样做。
  • 然后你可以有两个文件并从另一个文件运行一个文件。

标签: python multithreading parallel-processing multiprocessing


【解决方案1】:

感谢大家的帮助。每次执行 while 循环时,我最终只是在同一个窗口中重新渲染图形。对我来说效果很好,我可以完全避免使用多线程。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    • 2012-12-31
    • 2012-06-24
    • 1970-01-01
    • 1970-01-01
    • 2015-08-04
    相关资源
    最近更新 更多