Jump to content
toasterking

_RunWaitGet() - StdOut and StdErr stream capture

Recommended Posts

Someone told me I should post this in the examples section.  I wrote this to make it easy for me to call a Windows console application and get its output using a single line of AutoIt code.  I hope it's helpful to someone else.

 

#include <Constants.au3>

; Examples:
MsgBox(0,"Windows Version",_RunWaitGet(@ComSpec & " /c ver",1,"",@SW_HIDE))
MsgBox(0,"System Info",_RunWaitGet(@SystemDir & "\systeminfo.exe",1))

; #FUNCTION# ====================================================================================================================
; Name ..........: _RunWaitGet

; Description ...: Runs the specified process, waits for it to exit, then returns the contents of its StdOut and/or StdErr streams.
;                  Handy for running command-line tools and getting their output.
; Syntax ........: _RunWaitGet($sProgram, $nOptions, $sWorkingDir, $nShowFlag)
; Parameters ....: $sProgram            - The full path of the program (EXE, BAT, COM, or PIF) to run
;                  $nOptions            - Add options together:
;                                            1 = Capture the StdOut stream.
;                                            2 = Capture the StdErr stream.
;                                            4 = Return when the stream(s) close(s), not when the process ends.
;                  $sWorkingDir         - The working directory. Blank ("") uses the current working directory.
;                                         This is not the path to the program.
;                  $nShowFlag           - The "show" flag of the executed program:
;                                            @SW_SHOW = Show window (default)
;                                            @SW_HIDE = Hidden window (or Default keyword)
;                                            @SW_MINIMIZE = Minimized window
;                                            @SW_MAXIMIZE = Maximized window
; Return values .: String value containing the captured contents.
;                  If there was a problem running the process, @error is set to the @error value returned by Run().
;                  Otherwise, @error is 0.
; Author ........: ToasterKing

; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: MsgBox(0,"System Info",_RunWaitGet(@SystemDir & "\systeminfo.exe",1))
;                  MsgBox(0,"Windows Version",_RunWaitGet(@ComSpec & " /c ver",1,"",@SW_HIDE))
; ===============================================================================================================================
Func _RunWaitGet($sProgram,$nOptions = 0,$sWorkingDir = @SystemDir,$nShowFlag = @SW_SHOW)
    Local $nRunOptFlags = 0,$sStreamOut = "" ; Initialize variables
    ; Determine flags for parent/child interaction
    If BitAND($nOptions,1) Then $nRunOptFlags += $STDOUT_CHILD
    If BitAND($nOptions,2) Then $nRunOptFlags += $STDERR_CHILD
    Local $hRunStream = Run($sProgram,$sWorkingDir,$nShowFlag,$nRunOptFlags) ; Run the process
    If @error Then Return SetError(@error,@extended,0) ; If there was an error code, return it.  Otherwise...
    While 1 ; Loop until the end of the stream, which indicates that the process has closed it (which usually means the process ended)
        If BitAND($nOptions,1) Then ; If user specified to capture STDOUT stream...
            $sStreamOut &= StdoutRead($hRunStream) ; Append new stream contents to existing variable while removing those contents from the stream.
            If @error = 2 And BitAND($nOptions,4) Then ExitLoop ; If stream ended and user specified to return when the stream closes, stop looping.
        EndIf
        If BitAND($nOptions,2) Then ; If user specified to capture STDERR stream...
            $sStreamOut &= StderrRead($hRunStream) ; Append new stream contents to existing variable while removing those contents from the stream.
            If @error = 2 And BitAND($nOptions,4) Then ExitLoop ; If stream ended and user specified to return when the stream closes, stop looping.
        EndIf
        If Not BitAND($nOptions,4) And Not ProcessExists($hRunStream) Then ExitLoop ; If using the default setting and the process ended, stop looping.
        Sleep(100) ; To avoid overloading the CPU
    WEnd
    Return SetError(0,0,$sStreamOut) ; Return the captured contents and @error = 0
EndFunc

 

Share this post


Link to post
Share on other sites

That's not the sort of use I intended when I wrote the function, but this is AutoIt.  Of course there is a way.™

Try my scribblings below.  If you want something wrapped up in a nice, tidy function, that's an exercise for the reader.  :)

#include <Constants.au3>
#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#include <GuiEdit.au3>
$FormMain = GUICreate("Crappy Demo", 602, 297)
$EditStdOut = GUICtrlCreateEdit("", 16, 16, 569, 225, BitOR($ES_AUTOVSCROLL,$ES_WANTRETURN,$WS_VSCROLL))
$ButtonTraceRoute = GUICtrlCreateButton("Trace Route!", 240, 256, 115, 25)
GUISetState(@SW_SHOW)

While 1
    $nMsg = GUIGetMsg()
    Switch $nMsg
        Case $GUI_EVENT_CLOSE
            Exit
        Case $ButtonTraceRoute
            _TraceRoute()
    EndSwitch
WEnd

Func _TraceRoute()
    GUICtrlSetState($ButtonTraceRoute,$GUI_DISABLE)
    $hRunStream = Run(@SystemDir & "\tracert.exe www.autoitscript.com",@SystemDir,@SW_HIDE,$STDOUT_CHILD)
    While 1
        $sStreamOut = StdoutRead($hRunStream)
        If @error Then
            ExitLoop
        Else
            _GUICtrlEdit_AppendText($EditStdOut,$sStreamOut)
        EndIf
        Sleep(100)
    WEnd
    GUICtrlSetState($ButtonTraceRoute,$GUI_ENABLE)
EndFunc

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • By GillesMaisonneuve
      Good morning,
       
      I am trying to read a Unicode utf8 string from a perl subprocess via StdoutRead.
      I use an AUtoIt GUI and display result in an 'Edit' control (see my code below) using 'Courier New', a font that can handle Unicode characters.
      I was expecting a result looking like (CMD console):
      ++$ chcp 65001>NUL: & perl -Mutf8 -CS -e "use 5.018; binmode STDOUT,q(:utf8); say qq(\x{03A9})" & chcp 850>NUL: Ω Instead I get someting like this (see downward the screen copy):
      ++$ chcp 1250>NUL: & perl -Mutf8 -CS -e "use 5.018; binmode STDOUT,q(:utf8); say qq(\x{03A9})" & chcp 850>NUL: Ω Obviously while I was expecting to receive an utf8 char, it seems to have been converted to Windows ANSI codepage 1250 (Windows default for Western/Central Europe, right ?)
      What am I doing wrong? Is there someone who could guide me?
       
      Here is my code and my output in the GUI.
      Creating and configuring the Edit control:
      Local $Edit1 = GUICtrlCreateEdit( "", 20, 110, 780, 500, BitOr($GUI_SS_DEFAULT_EDIT,$ES_MULTILINE,$ES_READONLY) ) GUICtrlSetData($Edit1, "This field will contain text result from external Perl command") GUICtrlSetFont($Edit1, 10, $FW_THIN, $GUI_FONTNORMAL, "Courier New")  
      Executing Perl command (note: `-Mutf8` and `-CS` garantees that I work in utf8 and STDOUT accepts wide-characters):
      local $ExePath = 'perl.exe -Mutf8 -CS ' ;~ if perl in PATH, no need for full path C:\Perl\bin\perl.exe local $Params = '-e "use 5.018; use utf8; use charnames q(:full); binmode STDOUT,q(:utf8);' & _ 'say scalar localtime; say qq(\N{GREEK CAPITAL LETTER OMEGA})"' local $Cmd = $ExePath & ' ' & $Params Local $iPID = Run($Cmd, "", @SW_HIDE, BitOR($STDERR_CHILD, $STDOUT_CHILD))  
      Reading STDOUT and displaying it into the Edit control:
      While 1 $sOutput &= StdoutRead($iPID) If @error Then ; Exit the loop if the process closes or StdoutRead returns an error. ExitLoop EndIf WEnd If $sOutput <> '' Then GUICtrlSetData($Edit1, $sOutput) EndIf  
      And now, what I get on my GUI:
       

    • By Funtime60
      I have a Parent Script that starts multiple, concurrent child processes. I cannot figure out how to apply the technique for using StdoutRead in the examples in a way that listens to them all simultaneously.
      For reference, there can be any even number of, or single, child processes and there is an 1D array, $PIDS, that stores the PIDS of all the child processes and they should be outputting to another 1D array $sOutput.
      Thank you for your time. Please just point me in the right direction. I'm sorry if I missed another topic that covers this.
    • By ohaya
      Hi,
      I am trying to use ConsoleWrite() to output some debug to stdout/console on a Windows command (cmd) window, but it seems like nothing is being output.
      I noted that the help says:
      but what does that mean (the "compiled as a console application" part?
      I have also tried adding
      to the beginning of my .au3 and re-compiling, but when I run the .exe in a command window, nothing is being output?
      How do I get the output from ConsoleWrite() to appear?
      Thanks,
      Jim
    • By Blueman
      Hey Guys,

      I have a (i think) simple question, but i can't seem to get the answer though the help-files.
      Hope that you can help me with this issue.
      - I am opening a SSH Connection with the following function
      Func _Connect($session,$usr,$pass) $exec = @ScriptDir & "\PLINK.EXE" If Not FileExists($exec) Then _Err("PLINK.EXE Not Found!",0) $pid = Run($exec & " -load " & $session & " -l " & $usr & " -pw " & $pass, @ScriptDir, @SW_HIDE, 0x1 + 0x8) ;Run SSH.EXE If Not $pid Then _Err("Failed to connect",0) $currentpid = $pid ;$rtn = _Read($pid) ;Check for Login Success - Prompt ;MsgBox(48,"","1") ;sleep(5000) ;Wait for connection Return $pid EndFunc - This will connect to a CMS Server with a vt100 interface where a dynamic report is generated every 20 seconds.
      - Then i will read the contents with the following Function
      Func _Read($pid) $SSHREADTIMEOUT = 0 If Not $pid Then Return -1 Local $dataA Local $dataB Do $SSHREADTIMEOUT += 1 $dataB = $dataA sleep(100) $dataA &= StdOutRead($pid) If @error Then ExitLoop Until ($dataB = $dataA And $dataA And $dataB) OR $SSHREADTIMEOUT == 50 Return $dataA EndFunc This all goes correctly, but i can only read the contents once.
      When i try to read the contents again i get nothing.
      Maybe because the CMS isn't changing, but the values in the report is changing every 20 seconds.
      I need to somehow read al of the contents every time i perform a Read action, but how?
      Yes, i can use it in a While loop, but also then i get nothing or a small line of text and not the whole report.
       
      Any Idea?
       
      Thanks Guys!
       
      --Edit--
      I have fixed the problem by changing the terminal session to a vt220 session.
      The only problem now is that i want to send the: "Data link escape" command and that is something i cannot fix,.
      I have tried;
      StdinWrite($Pid,Hex(0x10)) StdinWrite($Pid,Chr(16)) StdinWrite($Pid,{DLE}) But nothing seems to work.  
      -- Edit-2 --
      Guys, fixed that too!
      Forgot to add the number '5' to actually execute the assignment.
      So fixed it by using;
       
      StdinWrite($Pid,Chr(16)) StdinWrite($Pid,"5")
      Thanks for reading with me
       
    • By rudi
      Hello,
      to provide an easy to use starter to capture traffic on all NICs found, I can successfully get all the interfaces of TSHARK.EXE (the command line version that's automatically installed along with wireshark) with this script:
      #include <AutoItConstants.au3> #include <Array.au3> $TS_WD = "C:\Program Files\Wireshark" $TS_exe = $TS_WD & "\tshark.exe" if not FileExists($TS_exe) Then MsgBox(48,"Fatal Error","No Wireshark Commandline Tool ""TSHARK.EXE"" found:" & @CRLF & _ $TS_exe) Exit EndIf $DString = "" $PIDGetIFs = Run($TS_exe & " -D", $TS_WD, @SW_HIDE, $STDERR_MERGED) While ProcessExists($PIDGetIFs) $DString &= StdoutRead($PIDGetIFs) WEnd ; MsgBox(0,"IFs",$DString) $aNICs = StringSplit($DString, @CRLF, 1) _ArrayDisplay($aNICs) $RegExIF = "^(?:\d+\. )(\\.*?})(?: \()(.*?)(\))$" ; $1 = TSHARK Interface Name, $2 = Windows Interface Name ; ... get the names to run TSHARK with the appropriate interface string  
      When I run TSHARK.EXE using this line directly, I see a continuously growing number telling the number of packets captured so far.
      "C:\Program Files\Wireshark\tshark.exe" -i \Device\NPF_{AEB931E9-E5FA-4DA5-8328-D87BDF53805C} -b duration:300 -b files:600 -w "y:\TShark-Ringbuffer\LAN-Verbindung\TSHARK-Com-0317_17---LAN-Verbindung___.pcap" Using this script, I *DO* see the first output line "Capturing on 'LAN-Verbindung'", but I cannot get hold of the continuously growing number of packets captured so far.
      #include <AutoItConstants.au3> $WD="C:\Program Files\Wireshark" $CMD='"C:\Program Files\Wireshark\tshark.exe" -i \Device\NPF_{AEB931E9-E5FA-4DA5-8328-D87BDF53805C} -b duration:300 -b files:600 -w "y:\TShark-Ringbuffer\LAN-Verbindung\TSHARK-Com-0317_17---LAN-Verbindung___.pcap"' ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $CMD = ' & $CMD & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console $PID=Run($CMD,$WD,@SW_SHOW,$stderr_merged) ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $PID = ' & $PID & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console $OutputAll="" While ProcessExists($PID) $output=StdoutRead($PID) $OutputAll&=$output ToolTip($OutputAll) if $output <> "" then ConsoleWrite("""" & $output & """" & @CRLF) Sleep(1000) WEnd ConsoleWrite("Process vanished" & @CRLF)  
      This is the output of SciTE, when I let TSHARK.EXE run for a short while, the "close" it's "box" ...
       
      --> Press Ctrl+Alt+Break to Restart or Ctrl+Break to Stop @@ Debug(10) : $CMD = "C:\Program Files\Wireshark\tshark.exe" -i \Device\NPF_{AEB931E9-E5FA-4DA5-8328-D87BDF53805C} -b duration:300 -b files:600 -w "y:\TShark-Ringbuffer\LAN-Verbindung\TSHARK-Com-0317_17---LAN-Verbindung___.pcap" >Error code: 0 @@ Debug(13) : $PID = 10948 >Error code: 0 "Capturing on 'LAN-Verbindung' " Process vanished  
      Howto catch the "growing-packet-number" TSHARK.EXE is writing continuously to the same "window position"???
       
       
      Regards, Rudi.
       


×
×
  • Create New...