是否可以通过命令提示符从 C# 运行 python 代码?

Sar*_*nan 2 c# python c#-4.0

我想通过命令提示符从 C# 运行 python 代码。代码附在下面

    Process p = new Process();
    p.StartInfo.FileName = "cmd.exe";
    p.StartInfo.WorkingDirectory = @"d:";
    p.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.RedirectStandardInput = true;

    p.Start();
    p.StandardInput.WriteLine(@"cd D:\python-source\mypgms");
    p.StandardInput.WriteLine(@"main.py -i example-8.xml -o output-8.xml");

    string output = p.StandardOutput.ReadToEnd();
    p.WaitForExit();

    Console.WriteLine("Output:");
    Console.WriteLine(output);

Output :

D:\python-source\mypgms>main.py -i example-8.xml -o output-8.xml

D:\python-source\mypgms>
Run Code Online (Sandbox Code Playgroud)

但什么也没发生。实际上 main.py 是我的主程序,它需要 2 个参数。一种是输入 xml 文件,另一种是转换后的输出 xml 文件。

但我不知道如何通过命令提示符从 C# 运行这个 python 脚本。请指导我摆脱这个问题......

感谢和问候, P.SARAVANAN

Dav*_*nan 5

我认为你执行cmd.exe是错误的。我想说你应该执行 python.exe,或者也许执行 main.py,并将 UseShellExecute 设置为 true。

目前,您的代码在 p.WaitForExit() 处阻塞,因为 cmd.exe 正在等待您的输入。您需要键入 exit 以使 cmd.exe 终止。您可以将其添加到您的代码中:

p.StandardInput.WriteLine(@"exit");
Run Code Online (Sandbox Code Playgroud)

但我会完全删除 cmd.exe 并直接调用 python.exe。据我所知,cmd.exe 只是增加了额外的复杂性,绝对没有任何好处。

我认为你需要这样的东西:

var p = new Process();
p.StartInfo.FileName = @"Python.exe";
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.Start();
p.WaitForExit();
Run Code Online (Sandbox Code Playgroud)

此外,Python 脚本似乎输出到文件而不是标准输出。因此,当您执行 p.StandardOutput.ReadToEnd() 时,那里将没有任何内容。