通过在.Net Core应用中运行Python脚本,可以非常方便的进行某些功能的处理。特别是考虑到Python是解释型语言,不需要像.Net 那样编译再部署。

通过使用NuGet中的IronPythonIronPython.StdLib:

public class PythonScript
{
    private ScriptEngine _engine;

    public PythonScript()
    {
        _engine = Python.CreateEngine();
    }

    public TResult RunFromString<TResult>(string code, string variableName)
    {
        // for easier debugging write it out to a file and call: _engine.CreateScriptSourceFromFile(filePath);
        ScriptSource source = _engine.CreateScriptSourceFromString(code, SourceCodeKind.Statements);
        CompiledCode cc = source.Compile();

        ScriptScope scope = _engine.CreateScope();
        cc.Execute(scope);

        return scope.GetVariable<TResult>(variableName);
    }
}

然后使用运行脚本:

var py = new PythonScript();
var result = py.RunFromString<int>("d = 8", "d");
Console.WriteLine(result);

原生的ProcessProcessStartInfo (个人实践出来的)

注意,需要通过执行含有Python可执行文件和参数的shell脚本来实现执行Python脚本, 有点绕,具体就是:

1, 创建一个run.batWindows系统:

C:\YOUR_PYTHON_PATH\python.exe %*

2, 创建一个run.sh文件给LInux系统:

#!/bin/bash
/usr/bin/python3 "[email protected]"

3, 使用Process and ProcessStartInfo 来运行脚本:

string fileName = null;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
    fileName = "path_to_bat/run.bat"
}
else
{
    fileName = "path_to_bat/run.sh"
}

ProcessStartInfo start = new ProcessStartInfo
{
    FileName = fileName,
    Arguments = string.Format("\"{0}\" \"{1}\"", script, args),
    UseShellExecute = false,
    CreateNoWindow = true,
    RedirectStandardOutput = true,
    RedirectStandardError = true
};
using Process process = Process.Start(start);

变量script指代需要执行的Python脚本所在位置,变量args指代脚本需要的参数,若有多个参数,酌情修改程序片段。

参考

  1. How to use Python in .NET-Core application?
  2. How to run python script from C# code by using command

标签: dotNet

评论已关闭