Forum > General

TProcess

(1/2) > >>

rjmatm:
I'm trying to run an external application, just an 'ls' from my Lazarus application.  I was trying the TProcess component but I have run into a couple issues.

1) When I try to set the TProcess to active I get a runtime error - 'Access Violation'

2) I'm not quite sure how to handle the output stream from the TProcess so I can make it a readable string and send it to something like a TMemo.

Any help or even a point to relavent documention would be greatly apprciated.

Thanks

Drewski:
add "dos" to your uses section.

procedure RunCommand(Exec: String; Args: String);
var
fExec: String;
begin
 // you cant use just 'ls' you have to have the full path: '/bin/ls' which is what this does.
 fExec := FileSearch(Exec, GetEnv('PATH'));
 if Length(fExec) > 0 then begin
   with TProcess.Create(self) do begin
     CommandLine := fExec +' ' + Args;
     Execute;
   end;
 end
 else ShowMessage('Couldn''t find the ' +Exec+ ' executable!');
end;

As for the stream I think you can use Lines.LoadFromStream, but I am pretty sure that will block until the TProcess ends.

HTH
Andrew

rjmatm:
Thanks Andrew.

The command seems to work, now I'm just fighting with the output stream.

rjmatm:
First, thanks again Andrew, you got me going in the right direction.

After fighting with the streams and getting access violation messages for a couple of hours I found an old post in the mailing list archives.  It was about setting an option for the TProcess to [poUseStreams], will that didn't work.  I found that the new component implementation of TProcess uses [poUsePipes], that did it!  

For the sake of everyone trying to do this and not finding an answer I'm posting my code below.  As of this post my IDE about is dated '29-5-2004', so this should work if you have the same one.

I just have a form with a button and a TMemo.

// CODE
procedure TForm1.Button1Click(Sender: TObject);
  var
  fExec: String;
  Args: String;
  WorkingDir: String;
 
begin

  // Directory to ls
  WorkingDir := '/etc';
  // Search listings in your profile $PATH to find the command.  In this case it's ls
  fExec := FileSearch('ls', GetEnv('PATH'));
  // Arguments for the command
  Args := '-la';

  if Length(fExec) > 0 then begin

    with TProcess.Create(self) do begin
      CurrentDirectory := WorkingDir;
      Options := [poUsePipes];
      CommandLine := fExec + ' ' + Args;
      Execute;
      Memo1.Lines.LoadFromStream(OutPut);
    end;

  end
  else

    begin
      ShowMessage('Couldn not find the executable!');
    end;

end;

Marc:

--- Quote from: "andyman" ---add "dos" to your uses section.

procedure RunCommand(Exec: String; Args: String);
....

--- End quote ---


Just for the record, the unit dos is only needed for the example and not for using tprocess

Navigation

[0] Message Index

[#] Next page

Go to full version