P.SARAVANAN 在 Stack Overflow 上提出一个问题,他想要从 C# 通过命令行运行 Python 代码,但他遇到一些问题。P.SARAVANAN 的 Python 脚本 main.py 需要两个参数,一个输入 XML 文件,另一个输出 XML 文件,他想在 C# 中使用 Process 类来执行 Python 脚本。
2、解决方案
为了解决 P.SARAVANAN 的问题,我们可以使用以下步骤:
- 使用
Process类创建一个新的进程,并设置StartInfo属性来指定要执行的 Python 脚本。 - 将
UseShellExecute属性设置为false,以便我们能够使用StandardInput和StandardOutput属性。 - 将
RedirectStandardOutput和RedirectStandardInput属性设置为true,以便我们能够读取 Python 脚本的输出并向 Python 脚本发送输入。 - 使用
StandardInput属性向 Python 脚本发送输入参数。 - 使用
StandardOutput属性读取 Python 脚本的输出。 - 等待进程结束。
以下代码展示了如何使用 Process 类从 C# 通过命令行运行 Python 代码:
using System;
using System.Diagnostics;
namespace PythonRunner
{
class Program
{
static void Main(string[] args)
{
// 创建新的进程
Process p = new Process();
// 设置要执行的 Python 脚本
p.StartInfo.FileName = "python.exe";
// 设置 Python 脚本的参数
p.StartInfo.Arguments = "main.py input.xml output.xml";
// 设置工作目录
p.StartInfo.WorkingDirectory = @"D:\python-source \mypgms";
// 设置窗口样式
p.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
// 设置不要使用外壳程序
p.StartInfo.UseShellExecute = false;
// 设置重定向标准输出和标准输入
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
// 启动进程
p.Start();
// 向 Python 脚本发送输入参数
p.StandardInput.WriteLine("This is a test input");
// 读取 Python 脚本的输出
string output = p.StandardOutput.ReadToEnd();
// 等待进程结束
p.WaitForExit();
// 输出 Python 脚本的输出
Console.WriteLine("Output:");
Console.WriteLine(output);
}
}
}
在上面的代码中,我们使用 Process 类创建一个新的进程,并设置 StartInfo 属性来指定要执行的 Python 脚本。将 UseShellExecute 属性设置为 false,以便我们能够使用 StandardInput 和 StandardOutput 属性。将 RedirectStandardOutput 和 RedirectStandardInput 属性设置为 true,以便我们能够读取 Python 脚本的输出并向 Python 脚本发送输入。然后,我们使用 StandardInput 属性向 Python 脚本发送输入参数,并使用 StandardOutput 属性读取 Python 脚本的输出。最后,我们等待进程结束,并输出 Python 脚本的输出。
希望这篇技术文章能够帮助您解决使用 C# 通过命令行运行 Python 代码的问题。