「hmPy・IronPython」の例題⑦ 外部プロセスの呼び出し

概要

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

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

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

#PY = loaddll( hidemarudir + @"\hmPy.dll" );

#_ = dllfuncw(#PY, "DoString", R"PY(
import clr

import System
from System.Diagnostics import Process

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

p = Process()

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

# 今回の例では、一般のプログラムではなく、(旧)DOS系のコンソールコマンド。「dir.exe」などというファイルがあるわけではなく…
p.StartInfo.FileName = System.Environment.GetEnvironmentVariable("ComSpec");

p.StartInfo.CreateNoWindow = False                # コンソールを開かない
p.StartInfo.UseShellExecute = False                # シェル機能を使用しない
p.StartInfo.RedirectStandardOutput  = True         # 標準出力をリダイレクト
p.StartInfo.RedirectStandardInput  = False         # 標準入力をリダイレクトはしない
p.StartInfo.Arguments       = command_args

p.Start()
output = p.StandardOutput.ReadToEnd()              # 標準出力の一気な読み取り
p.WaitForExit()
p.Close()

output.Replace("\r\r\n", "\n")                     # 改行コードの修正。
# 他にもIronPythonの段階で、.NETの正規表現クラス等を利用して、値をパースしていくことも容易でしょう。
# 少なくとも秀丸マクロでやるよりは何倍も簡単でエレガントな記述となるハズです。
hm.debuginfo(output)

hm.Macro.Var["$output"] = output

hm.Macro.Eval(r"""
    message $output
"""
);

)PY"
);

freedll( #PY );

PICTURE