Difference between revisions of "Executing External Programs/ja"

From Free Pascal wiki
Jump to navigationJump to search
Line 108: Line 108:
 
  end.
 
  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.
+
この見本ではpoWaitOnExitを使わず、プログラムの実行中に出力をメモリストリームに入れていきます。それをTStringListを使って読み出すことができます。
  
 
  program procoutlarge;
 
  program procoutlarge;
Line 136: Line 136:
 
   
 
   
 
  begin
 
  begin
   // We cannot use poWaitOnExit here since we don't
+
   // poWaintOnExitを使うことはできませんので
   // know the size of the output. On Linux the size of the
+
   // 出力のサイズがわかりません。
   // output pipe is 2 kB. If the output data is more, we
+
   // Linuxにおいては出力パイプの大きさが2kbです。
   // 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
+
   // Memorystreamは出力バッファとして使います。
 
    
 
    
 
   M := TMemoryStream.Create;
 
   M := TMemoryStream.Create;
Line 154: Line 154:
 
   while P.Running do
 
   while P.Running do
 
   begin           
 
   begin           
     // make sure we have room
+
     // メモリ空間を確保します
 
     M.SetSize(BytesRead + READ_BYTES);
 
     M.SetSize(BytesRead + READ_BYTES);
 
      
 
      
     // try reading it
+
     // 読んでいきます
 
     n := P.Output.Read((M.Memory + BytesRead)^, READ_BYTES);
 
     n := P.Output.Read((M.Memory + BytesRead)^, READ_BYTES);
 
     if n > 0  
 
     if n > 0  
Line 165: Line 165:
 
     end
 
     end
 
     else begin     
 
     else begin     
       // no data, wait 100 ms
+
       // データがないときは100 ms待ちます
 
       Sleep(100);  
 
       Sleep(100);  
 
     end;
 
     end;
 
   end;
 
   end;
   // read last part
+
   // 読み込みの最終段階です
 
   repeat
 
   repeat
     // make sure we have room
+
     // メモリ空間を確保します
 
     M.SetSize(BytesRead + READ_BYTES);
 
     M.SetSize(BytesRead + READ_BYTES);
     // try reading it
+
     // 読んでいきます
 
     n := P.Output.Read((M.Memory + BytesRead)^, READ_BYTES);
 
     n := P.Output.Read((M.Memory + BytesRead)^, READ_BYTES);
 
     if n > 0  
 
     if n > 0  

Revision as of 11:34, 4 April 2006

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.

巨大な出力を読み取る

いままでの見本では、プログラムの終了まで待って、既に書き終えた出力をその後に読み取っていました。でもプログラムが大量の出力を行う場合、パイプを通じて読み取る必要があります。しかし、呼ばれたプログラムが終わるまで、プログラムから読むことができません。

この見本ではpoWaitOnExitを使わず、プログラムの実行中に出力をメモリストリームに入れていきます。それを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
  // poWaintOnExitを使うことはできませんので
  // 出力のサイズがわかりません。
  // Linuxにおいては出力パイプの大きさが2kbです。
  // これ以上の大きさのデータを読むことはこの方法ではできません。
  // 従って行き詰まります。
  //
  // Memorystreamは出力バッファとして使います。
  
  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          
    // メモリ空間を確保します
    M.SetSize(BytesRead + READ_BYTES);
    
    // 読んでいきます
    n := P.Output.Read((M.Memory + BytesRead)^, READ_BYTES);
    if n > 0 
    then begin
      Inc(BytesRead, n);
      Write('.')
    end
    else begin     
      // データがないときは100 ms待ちます
      Sleep(100); 
    end;
  end;
  // 読み込みの最終段階です
  repeat
    // メモリ空間を確保します
    M.SetSize(BytesRead + READ_BYTES);
    // 読んでいきます
    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.