python - 使用 ASP .NET MVC 在文件 .py 中调用外部 python 函数
问题描述
在 ASP.NET MVC 应用程序中,我有一个 XML 文件。我还有一个 python 函数 execute(xml_file),它将这个 xml 文件作为 test.py 中的输入(用 python3 编写)。此函数将执行此 xml 文件并为我返回结果列表。我希望 ASP .NET 能够获取并显示该结果。如何在 ASP .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;
}
}
推荐阅读
- android - 为什么 Android Studio 显示 Code xml 像“� �”
- angular - angular 6 / ngx-translate 和动态 devextreme dxDatagrid 列
- node.js - Node.js“无法读取未定义的属性'长度'
- azure - Azure Durable Functions - 无法更改任务中心名称以支持并行版本控制
- linux - 安装 RPM 不会运行 .spec 中列出的所有 %install 操作
- azure - Azure 重置功能键?
- python - Python new_list = list(old_list) 不克隆列表
- unreal-engine4 - 如何根据虚幻中的文本大小和长度缩放对象?
- regex - 正则表达式包含根文件夹下的所有内容,但 2 个文件夹除外?
- c++ - 如何找到最小编号的索引编号。在一个数组中?