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

标签 python asp.net-core ironpython .net-core

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

最佳答案

试试这个

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;
            }
        }
    }
}

然后

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

关于python - 如何在 .NET-Core 应用程序中使用 Python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41064961/

相关文章:

Python 相当于 c++ find_if

python - 如何在某些条件下制作一个 numpy 数组?

ssl - 使用python爬虫发送亚马逊修改邮政编码接口(interface)时遇到疑似TLS指纹风控

c# - 处理 ASP.NET Core 1.0 上的大文件上传

bash - 从 Bash 命令在文本文件中查找和替换

Python Tkinter 模块不显示输出

c# - 如何在类库中访问 JWT User.Claims

c# - ASP.NET 核心。配置DI为不同的接口(interface)获取相同的对象

python - IronPython 与 numpy 的 Python 速度对比

ironpython - 有人在生产应用程序中使用 IronPython 吗?