using System;
using System.Collections.Generic;
using System.Threading;
using Newtonsoft.Json;
public class PythonResult
{
public bool Success { get; set; }
public bool TimedOut { get; set; }
public string StandardOutput { get; set; }
public string StandardError { get; set; }
}
public class PythonResponse
{
public bool Success { get; set; }
public string Result { get; set; }
public string Error { get; set; }
}
public class PythonSyncInvoker : IDisposable
{
private readonly PythonRunner _processHost;
// Pythonからstdout応答が来るまで
// Worker Threadを同期的に待機させるためのイベント
//
// false = 非シグナル状態
// Wait()すると待機する
//
private readonly ManualResetEventSlim _waitEvent = new ManualResetEventSlim(false);
// 同じPythonSyncInvokerに対して
// 複数Threadが同時にRun()しないようにする
private readonly object _runLock = new object();
// Pythonから最後に受信したstdout 1行
private string _latestOutput;
public PythonSyncInvoker(PythonRunner processHost)
{
_processHost =processHost ?? throw new ArgumentNullException(nameof(processHost));
// イベント購読はRun()ごとではなく
// コンストラクタで1回だけ行う
_processHost.OutputReceived +=
OnOutputReceived;
}
private void OnOutputReceived(string data)
{
// Pythonから受け取った
// 「今回の要求に対する応答JSON」
_latestOutput = data;
// Wait()しているWorker Threadを起こす
//
// Set()するとManualResetEventSlimは
// 「シグナル状態」になる
_waitEvent.Set();
}
public PythonResult Run(string input1,string input2,int timeoutMs = 5000)
{
// ManualResetEventSlimを1個だけ再利用するため、
// 同時Runは禁止する
lock (_runLock)
{
// 前回のSet()状態を解除する。
//
// 前回:
// Set()
// ↓
// Wait()解除
//
// のままだと、次回のWait()が
// 即座に通過してしまう。
//
// そのため新しい要求を送る前に
// 必ず非シグナル状態へ戻す。
_waitEvent.Reset();
// 前回の応答を消す
_latestOutput = null;
var request =
new List<string>
{
input1,
input2
};
string json =JsonConvert.SerializeObject(request);
// Pythonへ新しい要求を送信
_processHost.WriteInput(json);
// Pythonからstdoutが返るまで待機。
//
// OnOutputReceived()
// ↓
// _waitEvent.Set()
//
// が呼ばれるとここから再開する。
bool signaled =_waitEvent.Wait(timeoutMs);
// timeoutMs以内にstdout応答がなかった
if (!signaled)
{
return new PythonResult
{
Success = false,
TimedOut = true,
StandardError ="Python execution timed out."
};
}
try
{
// stdoutは
// 「1要求 = JSON 1行」
// という通信仕様
PythonResponse response =JsonConvert.DeserializeObject<PythonResponse>(_latestOutput);
if (response == null)
{
return new PythonResult
{
Success = false,
TimedOut = false,
StandardError ="Python response was null."
};
}
return new PythonResult
{
Success = response.Success,
TimedOut = false,
StandardOutput =response.Result,
StandardError =response.Error
};
}
catch (JsonException ex)
{
// stdoutに想定外の文字列が出ると
// JSONとして解析できない。
//
// Python側でprint()デバッグを
// stdoutへ出さないことも重要。
return new PythonResult
{
Success = false,
TimedOut = false,
StandardError =
"Invalid Python response: "
+ ex.Message
};
}
}
}
public void Dispose()
{
// コンストラクタで登録したイベントを解除
_processHost.OutputReceived -= OnOutputReceived;
_waitEvent.Dispose();
}
}
//worker側例
// PythonResult result =_pythonInvoker.Run(input1,input2);
// if (!result.Success)
// {
// OnPythonError?.Invoke(this,result.StandardError);
// }
//Main例
// private void HandlePythonError(object sender,string error)
// {
// if (InvokeRequired)
// {
// BeginInvoke(new Action<object, string>(^HandlePythonError),^sender,^error);
// return;
// }
// MessageBox.Show(\error,\"Python Error",\MessageBoxButtons.OK,\MessageBoxIcon.Error);
// }
//※py側は常駐ループの最上位1か所にtry-exceptを置くこと
// import json
// import traceback
// import sys
// while True:
// line = input()
// try:
// request = json.loads(line)
// input1 = request[0]
// input2 = request[1]
// result = execute(
// input1,
// input2
// )
// response = {
// "Success": True,
// "Result": result,
// "Error": None
// }
// except Exception:
// # traceback全体を1つの文字列として取得
// error_text = traceback.format_exc()
// # stderrにはログとして出してもよい
// print(
// error_text,
// file=sys.stderr,
// flush=True
// )
// # C#への正式な「処理完了応答」
// response = {
// "Success": False,
// "Result": None,
// "Error": error_text
// }
// # 成功でも失敗でも、
// # 必ずstdoutへJSONを1行だけ返す
// print(
// json.dumps(response),
// flush=True
// )