量化交易之nicegui篇 - web界面上运行其它脚本或指定脚本

展示如何在NiceGUI环境中构建一个应用,异步执行Python脚本(如hello.py和slow.py),并在界面上实时显示执行结果。用户可以通过按钮触发并传递参数给命令行程序。
摘要由CSDN通过智能技术生成
# main.py

import asyncio
import os.path
import platform
import shlex
import sys

from nicegui import ui


async def run_command(command: str) -> None:
    """Run a command in the background and display the output in the pre-created dialog."""
    dialog.open()
    result.content = ''
    command = command.replace('python3', sys.executable)  # NOTE replace with machine-independent Python path (#1240)
    process = await asyncio.create_subprocess_exec(
        *shlex.split(command, posix="win" not in sys.platform.lower()),
        stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT,
        cwd=os.path.dirname(os.path.abspath(__file__))
    )
    # NOTE we need to read the output in chunks, otherwise the process will block
    output = ''
    while True:
        new = await process.stdout.read(4096)
        if not new:
            break
        output += new.decode()
        # NOTE the content of the markdown element is replaced every time we have new output
        result.content = f'```\n{output}\n```'


with ui.dialog() as dialog, ui.card():
    result = ui.markdown()


ui.button('python3 hello.py', on_click=lambda: run_command('python3 hello.py')).props('no-caps')
ui.button('python3 slow.py', on_click=lambda: run_command('python3 slow.py')).props('no-caps')
with ui.row().classes('items-center'):
    ui.button('python3 hello.py "<message>"', on_click=lambda: run_command(f'python3 hello.py "{message.value}"')).props('no-caps')
    message = ui.input('message', value='NiceGUI')


ui.run(reload=platform.system() != 'Windows')
# hello.py

import sys

print(f'Hello, {sys.argv[1] if len(sys.argv) > 1 else "world"}!')
#. slow.py
import time

print('waiting 5 seconds...', flush=True)
time.sleep(5)
print('done')

代码运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值