VBScript - 从stdout捕获输出

时间:2015-10-03 08:52:27

标签: vbscript stdout aria2

我知道这已经在另一个问题中得到了解答,但我根本不明白它是如何完成的。

我试图将命令行程序(Aria2下载程序)的输出转换为HTA脚本,以便可以解析它,并且可以获取下载百分比,文件大小等,并动态更新为DIV。

以下是我调整过并尝试使用的代码,但它只是锁定界面,直到命令行完成,然后THEN显示所有输出,而不是显示它和它何时出现。

Const WshRunning = 0
Const WshFinished = 1
Const WshFailed = 2
strCommand = "ping.exe 127.0.0.1"

Set WshShell = CreateObject("WScript.Shell")
Set WshShellExec = WshShell.Exec(strCommand)

Do While WshShellExec.Status = WshRunning
    window.setTimeOut "", 100
Loop

Select Case WshShellExec.Status
    Case WshFinished
        strOutput = WshShellExec.StdOut.ReadAll()
    Case WshFailed
        strOutput = WshShellExec.StdErr.ReadAll()
End Select

Set objItem = Document.GetElementByID("status")
    objItem.InnerHTML = "" & strOutput & ""

如何修改它以便它不会锁定我的用户界面并抓取输出并在“状态”div中显示它?

1 个答案:

答案 0 :(得分:1)

问题是您的代码没有结束,将控件返回给浏览器。在程序结束之前,您不会离开循环,并且感知状态是接口挂起直到子进程结束。

您需要设置一个回调,以便浏览器定期调用您的代码,您将更新状态并离开。

<html>
<head>
    <title>pingTest</title>
    <HTA:APPLICATION
        APPLICATIONNAME="pingTest"
        ID="pingTest"
        VERSION="1.0"
    />
</head>

<script language="VBScript">
    Const WshRunning = 0
    Const WshFinished = 1
    Const WshFailed = 2

    Dim WshShellExec, Interval

    Sub Window_onLoad
        LaunchProcess
    End Sub

    Sub LaunchProcess
        Set WshShellExec = CreateObject("WScript.Shell").Exec("ping -n 10 127.0.0.1")
        Interval = window.setInterval(GetRef("UpdateStatus"),500)
    End Sub    

    Sub UpdateStatus
    Dim status 
        Set status = Document.GetElementByID("status")
        Select Case WshShellExec.Status
            Case WshRunning
                status.InnerHTML = status.InnerHTML & "<br>" & WshShellExec.StdOut.ReadLine()
            Case WshFinished, WshFailed
                status.InnerHTML = status.InnerHTML & "<br>" & Replace(WshShellExec.StdOut.ReadAll(),vbCRLF,"<br>")
                window.clearInterval(Interval)
                Interval = Empty
        End Select
    End Sub
</script>

<body>
    <div id="status"></div>
</body>
</html>