如何在 .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/