Executing External Programs/ja

From Free Pascal wiki
Jump to navigationJump to search

Deutsch (de) English (en) español (es) français (fr) italiano (it) 日本語 (ja) Nederlands (nl) polski (pl) português (pt) русский (ru) slovenčina (sk) 中文(中国大陆)‎ (zh_CN)

概要

外部のプログラムを動かすにはいくつかの方法がありますが、このチュートリアルではTProcessに限定して紹介しています。

TProcess

あなたはTProcessを使って外部プログラムを走らせることができます。TProcessを使用することによるメリットは次の通りです。

  • プラットホーム非依存
  • stdinからの読み込み、stdoutへの書き込みが可能

単純な見本

// これは外部プログラムを走らせてみる、デモプログラムです
program launchprogram;

// ここで関数や手続き使用するために
// ファイルをインクルードしておきます
uses 
  Classes, SysUtils, Process;

// "TProcess"型の"AProcess"
// という変数を定義しておきます

var 
  AProcess: TProcess;

// ここからプログラムが走ります
begin
  // TProcessオブジェクトを生成します
  // そしてそれを変数AProcessにアサインします
  AProcess := TProcess.Create(nil);

  // AProcessに実行するコマンドを伝えます
  // FreePascalコンパイラを走らせてみます
  AProcess.CommandLine := 'ppc386 -h';

  // ここでプログラムを走らせるときの、オプションを定義します
  // このオプションは、自分のプログラムを走らせたプログラムが
  // 停止するまで動かないようにします         vvvvvvvvvvvvvv
  AProcess.Options := AProcess.Options + [poWaitOnExit];

  // ここでAProcessが走ります。
  AProcess.Execute;

  // ppc386が停止するまで、これは実行されません。
  AProcess.Free;   
end.

これで自分のプログラムから、外部のプログラムを走らせる方法がわかりますね。

より向上した見本

いいですね、では自分では知らせたプログラムの出力を読むにはどうしたら良いでしょう?

では先ほどの例を改良して、それをやってみましょう。

// これはいかにして外部プログラムを走らせて、その出力を読むか
// 示したデモプログラムです。
program launchprogram;

// ここで関数や手続き使用するために
// ファイルをインクルードしておきます
uses 
  Classes, SysUtils, Process;

// This is defining the var "AProcess" as a variable 
// of the type "TProcess"
// Also now we are adding a TStringList to store the 
// data read from the programs output.
var 
  AProcess: TProcess;
  AStringList: TStringList;

// ここからプログラムが走ります
begin
  // TProcessオブジェクトを生成します
  // そしてそれを変数AProcessにアサインします
  AProcess := TProcess.Create(nil);

  // TStringListオブジェクトを生成します
  AStringList := TStringList.Create;

  // AProcessに実行するコマンドを伝えます
  // FreePascalコンパイラを走らせてみます
  AProcess.CommandLine := 'ppc386 -h';

  // ここでプログラムを走らせるときの、オプションを定義します
  // このオプションは、自分のプログラムを走らせたプログラムが
  // 停止するまで動かないようにします

  // また、ファイルの出力を読めるようにします

  AProcess.Options := AProcess.Options + [poWaitOnExit, poUsePipes];

  // AProcessはコマンドライン上で実行されるように実行されます
  AProcess.Execute;
  
  // ppc386が停止するまで、次にいきません

  // ここでTStringListに出力を読み込みます。
  AStringList.LoadFromStream(AProcess.Output);
  
  // ファイルに保存します
  AStringList.SaveToFile('output.txt');

  // 保存が完了したので
  // TStringListとTProcessを開放します
  AStringList.Free;
  AProcess.Free;   
end.

Reading large output

In the previous example we waited until the program exited. Then we read, what the program has written to its output. But suppose the program writes a lot of data to the output, the pipe becomes full and needs to read. But the calling program doesn't read from it, until the called program has ended. A dead lock occurs.

The following example therefore doesn't use poWaitOnExit, but reads from the output, while the program is still running. The output is stored in a memory stream, that can be used later to read the output into a TStringList.

program procoutlarge;
{
    Copyright (c) 2004 by Marc Weustink

    This example is creeated in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
}

uses
  Classes, Process, SysUtils;

const
  READ_BYTES = 2048;
  
var
  S: TStringList;
  M: TMemoryStream;
  P: TProcess;
  n: LongInt;
  BytesRead: LongInt;

begin
  // We cannot use poWaitOnExit here since we don't
  // know the size of the output. On Linux the size of the
  // output pipe is 2 kB. If the output data is more, we 
  // need to read the data. This isn't possible since we are 
  // waiting. So we get a deadlock here.
  //
  // A temp Memorystream is used to buffer the output
  
  M := TMemoryStream.Create;
  BytesRead := 0;

  P := TProcess.Create(nil);
  P.CommandLine := 'ppc386 -va bogus.pp';
  P.Options := [poUsePipes];
  WriteLn('-- executing --');
  P.Execute;
  while P.Running do
  begin          
    // make sure we have room
    M.SetSize(BytesRead + READ_BYTES);
    
    // try reading it
    n := P.Output.Read((M.Memory + BytesRead)^, READ_BYTES);
    if n > 0 
    then begin
      Inc(BytesRead, n);
      Write('.')
    end
    else begin     
      // no data, wait 100 ms
      Sleep(100); 
    end;
  end;
  // read last part
  repeat
    // make sure we have room
    M.SetSize(BytesRead + READ_BYTES);
    // try reading it
    n := P.Output.Read((M.Memory + BytesRead)^, READ_BYTES);
    if n > 0 
    then begin
      Inc(BytesRead, n);
      Write('.');
    end;
  until n <= 0;
  if BytesRead > 0 then WriteLn;
  M.SetSize(BytesRead); 
  WriteLn('-- executed --');
  
  S := TStringList.Create;
  S.LoadFromStream(M);
  WriteLn('-- linecount = ', S.Count, ' --');
  for n := 0 to S.Count - 1 do
  begin
    WriteLn('| ', S[n]);
  end;
  WriteLn('-- end --');
  S.Free;
  P.Free;
  M.Free;
end.

Example of "talking" with aspell process

Inside pasdoc source code you can find two units that perform spell-checking by "talking" with running aspell process through pipes:

  • PasDoc_ProcessLineTalk.pas unit implements TProcessLineTalk class, descendant of TProcess, that can be easily used to talk with any process on a line-by-line basis.
  • PasDoc_Aspell.pas units implements TAspellProcess class, that performs spell-checking by using underlying TProcessLineTalk instance to execute aspell and communicate with running aspell process.

Both units are rather independent from the rest of pasdoc sources, so they may serve as real-world examples of using TProcess to run and communicate through pipes with other program.