如何使用Mac一次运行Python多处理代码?

问题描述

我正在尝试创建一个带有破折号的实时仪表板,以读取由Simpy模拟同时创建的数据。 Simpy仿真将数据写入sqlite3数据库,并由破折号读取。

Simpy模拟和仪表板必须同时运行,因此我使用python的多处理库来启动仪表板,然后运行代码(根据https://community.plotly.com/t/multithreading-problem-with-parallel-tasks-streaming-data-and-pass-it-into-dash-app/22318/3中的解决方案)。现在可以运行,但是问题是我的主代码运行了两次。

我尝试添加一个if __name__ is __main__:语句,但是代码仍然运行两次。这是因为孩子的名字也得到了名字__main__

有人对如何确保代码仅运行一次有想法吗?也欢迎有关如何同时运行Dash仪表板和Simpy模拟器的任何想法。我正在使用Mac。

一个最小的代码示例:

main.py:


if __name__ == "__main__":

    import time
    import sqlite3
    import datetime
    import pandas as pd
    import multiprocessing as mp
    from app import app
    from utils import start_server

    start_server(app,mp)
    time.sleep(5)
    start = datetime.datetime.Now() 
    print("This is the start time",start)
    simpy_simulation()
    print("Running time",datetime.datetime.Now()-start)

utils.py:


def start_server(app,mp):
    def run():
        app.run_server(debug = True,processes=4,threaded=False)

    #Run on a separate process so that it doesn't block
    s = mp.Process(target=run)
    s.start()

app.py:


import dash
import sqlite3
import pandas as pd
import dash_daq as daq
import plotly.express as px
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input,Output

app = dash.Dash(__name__)

app.layout = html.Div([

    dcc.Interval(
        id='interval-component',interval=5*1000,# in milliseconds
        n_intervals=0
    ),html.Div([
        daq.Gauge(
            id='gauge-chart',value=2,max=100,min=0,units="MPH",)
    ]),])

@app.callback(
    Output('gauge-chart','value'),[Input('interval-component','n_intervals')]
)
def update_gauge(n_intervals):
    value = rnd.uniform(0,100)
    return value
     

收到的输出


   This is the start time 2020-11-05 09:57:58.746291
   Running time 0:00:00.000361
   This is the start time 2020-11-05 09:58:00.854131
   Running time 0:00:00.000462

预期输出


   This is the start time 2020-11-05 09:57:58.746291
   Running time 0:00:00.000361

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)