在ASP.NET MVC应用程序中,我有一个XML文件。我还有一个python函数execute(xml_file),它将此xml文件作为test.py中的输入(用python3编写)。此函数将执行此xml文件并返回结果列表。我希望ASP .NET能够获得结果并显示出来。我如何在ASP .NET MVC中调用该外部模块?
答案 0 :(得分:0)
你可以在C#代码上启动一个新的Process
来运行python并运行你的脚本。
你可以启动一个调用python的新进程。请参阅带有注释的示例:
ProcessStartInfo start = new ProcessStartInfo();
// full path of python exe
start.FileName = "c:\\Python\\Python.exe";
string cmd = "C:\\scripts\\test.py";
string args = "";
// define the script with arguments (if you need them).
start.Arguments = string.Format("\"{0}\" \"{1}\"", cmd, args);
// Do not use OS shell
start.UseShellExecute = false;
// You do not need new window
start.CreateNoWindow = true;
// Any output, generated by application will be redirected back
start.RedirectStandardOutput = true;
// Any error in standard output will be redirected back (for example exceptions)
start.RedirectStandardError = true;
// start the process
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
// Here are the exceptions from our Python script
string stderr = process.StandardError.ReadToEnd();
// Here is the result of StdOut(for example: print "test")
string result = reader.ReadToEnd();
return result;
}
}