首页 > 解决方案 > 使用 ASP .NET MVC 在文件 .py 中调用外部 python 函数

问题描述

在 ASP.NET MVC 应用程序中,我有一个 XML 文件。我还有一个 python 函数 execute(xml_file),它将这个 xml 文件作为 test.py 中的输入(用 python3 编写)。此函数将执行此 xml 文件并为我返回结果列表。我希望 ASP .NET 能够获取并显示该结果。如何在 ASP .NET MVC 中调用该外部模块?

标签: pythonasp.net-mvc

解决方案


您可以在 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;
    }
}

推荐阅读