进程运行时Django显示shell输出命令

2024-06-26 18:00:39 发布

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

我正在构建一个基于django的web应用程序,它需要运行shell命令。例如:我需要显示ping命令的实时输出。包括以下结构:

Django视图:

<div class="output-panel">
     <span class="live-output">OUTPUT HERE</span>
</div>
<button onclick="runCommand()">Run Command</button>

Javascript代码:

^{pr2}$

Django函数(/api/runCommand url转到api.runCommand)公司名称:

import subprocess
def runCommand(request):
    cmd = "ping google.com"
    process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    while True:
    nextline = process.stdout.readline()

    if nextline == '' and process.poll() is not None:
        break
    sys.stdout.write(nextline)
    sys.stdout.flush()

有没有办法把系统标准输出每次它生成一个新的输出行时都回到我的视图?(不是在进程完成时,而是与正在运行的进程一起)。在


Tags: django命令div视图outputstdoutbuttonshell