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

2024-03-29 12:20:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个带有dash的实时仪表板,该仪表板可以读取Simpy模拟同时创建的数据。Simpy模拟将数据写入sqlite3数据库,dash读取数据

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

Tags: 代码importappdatetimeservertimeismain