How to use Python in .NET-Core application? I need this for the purposes of Hackathon so the solution don't have to be 'elegant'. I've read that it's impassible to run Python scripts directly because there exists only library IronPython for standard ASP.NET but no for .NET-Core. So what is the simplest way to use Python scripts? (Because it's hackathon it's ok to use even PHP server or selenium etc. only to execute script)
如何在.NET-Core应用程序中使用Python?我需要这个用于Hackathon的目的,所以解决方案不必是“优雅的”。我已经读过,直接运行Python脚本是不可能的,因为标准ASP.NET只存在库IronPython但.NET-Core没有。那么使用Python脚本最简单的方法是什么? (因为它是hackathon,甚至可以使用PHP服务器或selenium等来执行脚本)
1 个解决方案
#1
8
Try this
尝试这个
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;
}
}
}
}
Then
然后
var res = new RunCmd().Run("your_python_file.py","params");
Console.WriteLine(res);
#1
8
Try this
尝试这个
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;
}
}
}
}
Then
然后
var res = new RunCmd().Run("your_python_file.py","params");
Console.WriteLine(res);