如何在.NET-Core应用程序中使用Python?

Mac*_*cki 15 python ironpython .net-core asp.net-core

如何在.NET-Core应用程序中使用Python?我需要这个用于Hackathon的目的,因此解决方案不必是"优雅的".我已经读过,直接运行Python脚本是不可能的,因为标准ASP.NET只存在库IronPython但.NET-Core没有.那么使用Python脚本最简单的方法是什么?(因为它是黑客马拉松,甚至可以使用PHP服务器或selenium等来执行脚本)

小智 16

试试这个

public class RunCmd
{
    public string Run(string cmd, string args)
    {
        ProcessStartInfo start = new ProcessStartInfo();
        start.FileName = "python";
        start.Arguments = string.Format("\"{0}\" \"{1}\"", cmd, args);
        start.UseShellExecute = false;// Do not use OS shell
        start.CreateNoWindow = true; // We don't need new window
        start.RedirectStandardOutput = true;// Any output, generated by application will be redirected back
        start.RedirectStandardError = true; // Any error in standard output will be redirected back (for example exceptions)
        using (Process process = Process.Start(start))
        {
            using (StreamReader reader = process.StandardOutput)
            {
                string stderr = process.StandardError.ReadToEnd(); // Here are the exceptions from our Python script
                string result = reader.ReadToEnd(); // Here is the result of StdOut(for example: print "test")
                return result;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后

 var res = new RunCmd().Run("your_python_file.py","params");
 Console.WriteLine(res);
Run Code Online (Sandbox Code Playgroud)


Jam*_*mes 6

由于这是 Google 中的第一批条目之一,因此您可能还应该提到 IronPython 现在完全支持 .NetCore,并且可以使用 NuGet 轻松安装。

这种方法更简单,因为它的代码行更少,安装和管理的运行时更少。另外,保持进程内执行有很多好处(性能、调试、类型安全等)。

  1. 使用 NuGet,添加最新的“IronPython”和“IronPython.StdLib”。 或者,将以下内容添加到项目文件中:
<Project Sdk="Microsoft.NET.Sdk">
  <ItemGroup>
    <PackageReference Include="IronPython" Version="2.7.10" />
    <PackageReference Include="IronPython.StdLib" Version="2.7.10" />
  </ItemGroup>
  ...
Run Code Online (Sandbox Code Playgroud)
  1. 创建一个函数或类以使运行脚本更方便:
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);
    }
}
Run Code Online (Sandbox Code Playgroud)
  1. 运行你的脚本:
var py = new PythonScript();
var result = py.RunFromString<int>("d = 8", "d");
Console.WriteLine(result);
Run Code Online (Sandbox Code Playgroud)