[fpc-pascal] Interactive process with TProcess
leledumbo
leledumbo_cool at yahoo.co.id
Tue Dec 16 09:43:02 CET 2008
OK, since no one answers this in Lazarus forum, I'll ask here as it's more
FPC (FCL, actually) related than LCL. I want to create an interactive
process, so I need to read the output as soon as it's available and write it
to the screen (or somewhere else). Here's the partial code (a little
different from the original post to avoid visual component):
var
CmdProcess: TProcess;
MemStr: TMemoryStream;
StrList: TStringList;
n: Integer;
ErrMsg: PChar;
begin
try
CmdProcess:=TProcess.Create(nil);
MemStr:=TMemoryStream.Create;
StrList:=TStringList.Create;
MemStr.SetSize(READ_BYTES);
with CmdProcess do begin
CommandLine:=InputStr;
Options:=[poUsePipes,poStderrToOutPut];
ShowWindow:=swoHide;
Execute;
while Running do begin
n:=Output.Read(MemStr.Memory^,READ_BYTES);
if n>0 then begin
StrList.LoadFromStream(MemStr);
WriteLn(StrList.Text);
MemStr.Clear;
end else
Sleep(100);
end;
end;
except
on e: EProcess do begin
{$IFDEF Windows}
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER or FORMAT_MESSAGE_FROM_SYSTEM,
nil,GetLastError,MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),
@ErrMsg,0,nil
);
{$ELSE}
ErrMsg:=@e.Message[1];
{$ENDIF}
WriteLn(ErrMsg);
Exit;
end;
on e: Exception do begin
MessageDlg('Error',e.Message,mtError,[mbOK],0);
Exit;
end;
end;
repeat
n:=CmdProcess.Output.Read(MemStr.Memory^,READ_BYTES);
if n>0 then begin
StrList.LoadFromStream(MemStr);
WriteLn(StrList.Text);
end;
until n<=0;
StrList.Free;
MemStr.Free;
CmdProcess.Free;
end;
--
View this message in context: http://www.nabble.com/Interactive-process-with-TProcess-tp21029222p21029222.html
Sent from the Free Pascal - General mailing list archive at Nabble.com.
More information about the fpc-pascal
mailing list