simple-GetCommandOutput-function.md 2.4 KB

Free Pascal GetCommandOutput function

Run program and get output without thinking too much about putting parameters on array

I made this to utilize both the cross platform TProcess and get output with a short code in Lazarus projects. I tested this on Linux so far but it should work with Windows and other platforms as well.

Usage

Create a new Application Project (Project - New Project - Application - OK.)

Put a new TMemo and a TButton. Double click the button, then enter:

procedure TForm1.Button1Click(Sender: TObject);
begin
  memo1.Text := GetCommandOutput('uname -rms');
end;

Now before the line end. put the TForm1.GetCommandOutput code from the codes heading below. With your cursor on the function name, press Ctrl+Shift+C. Don't forget to confirm if there is the Process unit under uses. Now Run - Run, then click the button.

This should output something like Linux 5.1.2_3 x86_64 in the memo textbox. On Windows, the uname command will not work. So you may want to try something Windows specific.

Code

program example;

// ...

{$mode objfpc}{$H+}

uses
  Process;

// ...

// Allows to run the command without thinking about putting
// parameters in an array. (i.e. Memo1.Text := GetCommandOutput('uname -rms');)
// This uses RunCommand, so it is compatible with TProcess.
function TForm1.GetCommandOutput(Command:string):string;
var
  s, binary: ansistring;
  Params: TStringArray;
  i,ArrLength:Cardinal;
begin
  // We get everything split by spaces.
  // We will consider every item as a parameter.
  // The first item will be our binary, so we keep it separate.
  Params := Command.Split(' ');
  binary:=Params[0];
  // Prepare the Params array
  // Remove the binary item from array
  ArrLength:=Length(Params);
  for i := 1 to ArrLength - 1 do
    Params[i - 1] := Params[i];
  SetLength(Params, ArrLength-1);

  // At the end run the command.
  if RunCommand(binary, Params, s) then
    Result := s;
end;

For Linux, a smaller version can be used. The benefit of this is that it support pipes (|), > and other shell related stuff:

function TForm1.GetCommandOutput(Command:string):string;
var
  s: ansistring;
begin
  if FileExists('/bin/sh') then begin
    if RunCommand('/bin/sh', ['-c', Command], s) then
      // We use Trim() to cut off access carriage return at the end
      Result := Trim(s);
  end;
end;