[Lazarus] Reading and Writing to TProcess

2014-04-12 Thread Richard Mace
Hi All,
I have the following code working well with TProcess outputting to a TMemo,
however, what I'd like to do it monitor the output and then when a certain
string is detected, I'd like to feed back to the process. That is, if the
TProcess outputs a question, I'd like to feed back either a "y" or a "n" as
if the user pressed it manually.

Hope that makes sense

Any ideas where to tweak?

Thanks Richard

const
  C_BUFSIZE = 2048;
var
  Hbk: TProcess;
  Buffer: pointer;
  SStream: TStringStream;
  nread: longint;
begin
  Hbk := TProcess.Create(nil);

  // Replace the line below with your own command string
  Hbk.CommandLine := 'c:\windows\system32\cmd.exe /c dir c:\windows\*.*';
  //

  Hbk.Options := [poUsePipes];
  Hbk.Execute;

  // Prepare for capturing output
  Getmem(Buffer, C_BUFSIZE);
  SStream := TStringStream.Create('');

  // Start capturing output
  while Hbk.Running do
  begin
nread := Hbk.Output.Read(Buffer^, C_BUFSIZE);
if nread = 0 then
  sleep(100)
else
  begin
// Translate raw input to a string
SStream.size := 0;
SStream.Write(Buffer^, nread);
// And add the raw stringdata to the memo
Memo1.Lines.Text := Memo1.Lines.Text + SStream.DataString;
  end;
  end;

  // Capture remainder of the output
  repeat
nread := Hbk.Output.Read(Buffer^, C_BUFSIZE);
if nread > 0 then
begin
  SStream.size := 0;
  SStream.Write(Buffer^, nread);
  Memo1.Lines.Text := Memo1.Lines.Text + SStream.Datastring;
end
  until nread = 0;

  // Clean up
  Hbk.Free;
  Freemem(buffer);
  SStream.Free;
end;
--
___
Lazarus mailing list
Lazarus@lists.lazarus.freepascal.org
http://lists.lazarus.freepascal.org/mailman/listinfo/lazarus


Re: [Lazarus] Reading and Writing to TProcess

2014-04-12 Thread leledumbo
You can do it around here:

nread := Hbk.Output.Read(Buffer^, C_BUFSIZE);
if nread = 0 then
  sleep(100)
else
  begin
// Translate raw input to a string
SStream.size := 0;
SStream.Write(Buffer^, nread);
// And add the raw stringdata to the memo
Memo1.Lines.Text := Memo1.Lines.Text + SStream.DataString;
  end;

Instead of directly flushing SStream contents to Memo1, I suggest keep
appending Buffer to SStream and detect the string you're looking for after
SStream.Write. When you've found it (and ensure the process already waits
for input), you can call Hbk.Input.Write methods (it has several overloads,
figure out which one is the best for you). Remember that normally process
waits for newline before processing input, so you might want to append that
to your input data.



--
View this message in context: 
http://free-pascal-lazarus.989080.n3.nabble.com/Lazarus-Reading-and-Writing-to-TProcess-tp4036656p4036661.html
Sent from the Free Pascal - Lazarus mailing list archive at Nabble.com.

--
___
Lazarus mailing list
Lazarus@lists.lazarus.freepascal.org
http://lists.lazarus.freepascal.org/mailman/listinfo/lazarus