在短划线中单击按钮时运行python脚本

2024-06-16 10:15:55 发布

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

我正在使用python Dash开发一个多页面的仪表板。在主页上,我创建了一个带有“提交”按钮的布局。因此,当用户选择选项并单击Submit按钮时,它应该调用另一个.py脚本,并在同一页面上显示该脚本

Index.py是主程序 Layout.py具有布局 new1.py的布局具有“提交按钮” new2.py是需要在单击submit按钮时显示的脚本

下面是new1.py中的代码,我在其中声明了按钮

html.Button('Clear',id='clear_button', n_clicks=0,  style = { 'width' : '30%', 'margin-top': '15vw', "margin":"15px" ,'border-radius': '8px'}),
            

具有回调按钮的Index.py

@app.callback(
   dash.dependencies.Output('apply_button', 'children'),
   [dash.dependencies.Input('button', 'n_clicks')])
def run_script_onClick(n_clicks):
  
   if not n_clicks:
       raise PreventUpdate
       
       script_path = 'python new2.py'

      call(["python3", script_path])
    
       
   
      return output_content 

这是正确的吗?当我点击应用按钮时,什么都没有出现。我希望new2.py的输出显示在同一屏幕上。另外,我应该在哪里给出回电声明。在Index.py中还是在new1.py中?有人能帮忙吗

谢谢, 普拉塔普


Tags: pathpymargin脚本声明indexscriptdependencies
1条回答
网友
1楼 · 发布于 2024-06-16 10:15:55

函数os.system()直接在屏幕上发送文本(到控制台),它只返回error code(数字0表示OK),所以不能将此文本分配给变量或使用return发送。如果您使用subprocess.call(),那么您也会遇到同样的问题。您需要模块subprocess-中的其他函数,即subprocess.run()subprocess.check_output()

在某些情况下,您可能需要使用Python-ie的完整路径。有时,使用脚本的完整路径也很好,因为代码可能会运行在您期望的不同文件夹中-您可以使用print( os.getcwd() )检查Current Working directory


这是我在Linux上的最小工作代码

我删除了style,因为它在这个问题中并不重要,我不使用from ... import ...来显示哪些命令来自subprocess,哪些命令来自dash

import dash
import dash_html_components as html
import subprocess

app = dash.Dash(__name__)

app.layout = html.Div(children=[
                       html.Div([            
                       html.Button('Apply', id='apply-button', n_clicks=0),
                       html.Div(id='output-container-button', children='Hit the button to update.')
                      ])
                ])                      
                
@app.callback(
    dash.dependencies.Output('output-container-button', 'children'),
    [dash.dependencies.Input('apply-button', 'n_clicks')])
def run_script_onClick(n_clicks):
    #print('[DEBUG] n_clicks:', n_clicks)
    
    if not n_clicks:
        #raise dash.exceptions.PreventUpdate
        return dash.no_update

    # without `shell` it needs list ['/full/path/python', 'script.py']           
    #result = subprocess.check_output( ['/usr/bin/python', 'script.py'] )  

    # with `shell` it needs string 'python script.py'
    result = subprocess.check_output('python script.py', shell=True)  

    # convert bytes to string
    result = result.decode()  
    
    return result
            
if __name__ == "__main__":
    app.run_server(port=8080, debug=True)

script.py

import datetime

print(datetime.datetime.now().strftime("%Y.%m.%d %H:%M:%S"))

编辑:

如果您想创建多页,那么应该使用import加载代码,运行它并创建新的布局对象,如https://dash.plotly.com/urls

使用subprocess您只能创建带有HTML的字符串,而不能创建布局对象

相关问题 更多 >