2013-07-12 86 views
2

我試圖寫這個代碼在AutoIT中,我如何運行子進程並一次捕獲一行輸出?

Local $foo = Run(@ComSpec & " /c dir", '', 0, 2) 
    Local $line 
    While 1 
     $line = StdoutRead($foo) 
     If @error Then ExitLoop 
     $line = StringStripCR($line) 
     if StringLen($line) > 0 then ConsoleWrite("START" & $line & "END" & @crlf) 
    WEnd 

和我有望獲得在每次一行,而是我有時得到2,3,50行取決於在月球上的相位。跆拳道?

回答

3

問題是StdoutRead(...)沒有用換行符分割成部分,它只是返回數據塊。您必須手動將數據解析爲行。此代碼有效:

Local $foo = Run(@ComSpec & " /c dir", '', 0, 2) 
Local $line 
Local $done = False 
Local $buffer = '' 
Local $lineEnd = 0 
While True 
    If Not $done Then $buffer &= StdoutRead($foo) 
    $done = $done Or @error 
    If $done And StringLen($buffer) == 0 Then ExitLoop 
    $lineEnd = StringInStr($buffer, @LF) 
    ; last line may be not LF terminated: 
    If $done And $lineEnd == 0 Then $lineEnd = StringLen($buffer) 
    If $lineEnd > 0 Then 
     ; grab the line from the front of the buffer: 
     $line = StringLeft($buffer, $lineEnd) 
     $buffer = StringMid($buffer, $lineEnd + 1) 

     ConsoleWrite("START" & $line & "END" & @CRLF) 
    EndIf 
WEnd 
相關問題