C#からPythonのインストールとライブラリの導入確認をします。
これによってC#からPythonのアプリケーションを適切に起動したりできます。
今後これらを使いC#からPython機械学習アプリケーションを呼び出して、
連携をしていこうと考えているところです。
動作環境
Windows 10
Python 3.6.4 Anaconda, Inc.
(環境変数にpythonは追加済み)
フォルダ構成
AppDir
|_ python
|_ import_check.py (import確認したいライブラリを記載)
|_ app.exe (PythonチェックをするC#アプリケーション)
ソースコード
Python (import確認用)
importできるか確認したいライブラリをまとめて記載
import_check.py
import pandas
import numpy
import opencv
# 他に適宜追加
C# (Pythonチェックアプリケーション)
関数を記載します。
適宜呼び出して利用してください。
app.cs
/// <summary>
/// Pythonがインストールされているか確認
/// </summary>
/// <param name="version">インストール済みPythonのバージョン</param>
public bool IsInstalledPython(ref string version)
{
Console.WriteLine("IsInstalledPython start...");
bool isInstalled = false;
ProcessStartInfo proc = new ProcessStartInfo();
proc.FileName = @"cmd.exe";
proc.Arguments = "/c python --version";
proc.CreateNoWindow = true;
proc.UseShellExecute = false;
proc.RedirectStandardOutput = true;
proc.RedirectStandardError = true;
Process prc = Process.Start(proc);
prc.WaitForExit();
StreamReader sr = prc.StandardError;
string strOut = sr.ReadToEnd();
// エラーなしの場合Pythonインストール済み
if (strOut.Contains("3."))
{
isInstalled = true;
try // バージョンも取得
{
version = strOut.Substring(strOut.IndexOf("3."), 5);
Console.WriteLine(version);
}
catch { }
}
return isInstalled;
}
/// <summary>
/// 指定したPythonライブラリが存在するか確認
/// 確認したいライブラリはpython\import_check.py にimportする
/// </summary>
/// <param name="libName"></param>
public bool IsInstalledPythonLib(ref string errMsg)
{
Console.WriteLine("IsInstalledPythonLib start...");
Process prc = new Process();
prc.StartInfo.FileName = "python.exe";
prc.StartInfo.Arguments = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"python\import_check.py");
prc.StartInfo.RedirectStandardError = true; // エラー出力取得に必要
prc.StartInfo.UseShellExecute = false;
prc.StartInfo.CreateNoWindow = true;
prc.Start();
prc.WaitForExit();
// エラーの取得
StreamReader sr;
sr = prc.StandardError;
errMsg += sr.ReadToEnd();
Console.WriteLine(errMsg);
bool isInstalled = true;
if (errMsg.Contains("ModuleNotFoundError")) // どれか1つでもImportエラーが出た
{
isInstalled = false;
}
return isInstalled;
}
参考
Python
WPF Check if python installed on system
C Sharp
DOSコマンドを実行し出力データを取得する
更新履歴
2021/10/26 初版
↧