「hmV8」の例題 外部プロセスの呼び出し

概要

hmV8の例題のひとつとなります。

外部プロセスを呼び出し、結果を文字列で受け取る

すでに存在する外部のプロセスを呼び出して処理をする、といったシーンは現在もそれなりに存在します。
特にコンソールコマンドの類はその傾向があることでしょう。

#JS = loaddll( hidemarudir + @"\hmV8.dll" );

// 外部プログラムを実行して出力結果を得る。
#_ = dllfuncw(#JS, "DoString", R"JS(

// let command = "cmd.exe";
let command_args = "/c dir";

let p = new clr.System.Diagnostics.Process();

// p.StartInfo.FileName = command; // 一般的なプログラムならこれで良い。実行するコマンドを秀丸からもらう

// しかし、今回の例では、一般のプログラムではなく、(旧)コンソールコマンド。「dir.exe」という実態ファイルがあるわけではないのでこのように対処
p.StartInfo.FileName = clr.System.Environment.GetEnvironmentVariable("ComSpec");

p.StartInfo.CreateNoWindow = true;                 // コンソールを開かない
p.StartInfo.UseShellExecute = false;               // シェル機能を使用しない
p.StartInfo.RedirectStandardOutput = true;         // 標準出力をリダイレクト
p.StartInfo.RedirectStandardInput = false;         // 標準入力をリダイレクトはしない
p.StartInfo.Arguments = command_args;              // コマンドの引数

p.Start();
let output = p.StandardOutput.ReadToEnd();         // 標準出力の一気に読み取り
p.WaitForExit();
p.Close();
 
output.replace( /\r\r\n/g, "\n" )                  // 改行コードの修正。
// NETの正規表現クラス等を利用して、値をパースしていくことも容易でしょう。
// 少なくとも秀丸マクロでやるよりはとても簡単でエレガントな記述となるハズです。

hm.debuginfo(output);
 
hm.Macro.Var["$output"] = output;
 
hm.Macro.Eval(
f => { /*
    message $output;
*/ }
);

)JS"
);

// 解放
freedll(#JS);

PICTURE