是否可以通过命令提示符从C#运行python代码? [英] Is this possible to run a python code from C# through command prompt?

查看:174
本文介绍了是否可以通过命令提示符从C#运行python代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to run python code from C# through command Prompt.The Code is attached below

    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>

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

But nothing happened.Actually main.py is my main program and it takes 2 arguments. one is input xml file and another one is converted output xml file.

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

But i dont know how to run this python script from C# through command prompt. Please Guide me to get out of this issue...

感谢与amp;问候,
P.SARAVANAN

Thanks & Regards, P.SARAVANAN

推荐答案

我认为您在执行cmd.exe时出错。我想说您应该执行python.exe,或者执行UseShellExecute设置为true的main.py。

I think you are mistaken in executing cmd.exe. I'd say you should be executing python.exe, or perhaps executing main.py with UseShellExecute set to true.

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

At the moment, your code blocks at p.WaitForExit() because cmd.exe is waiting for your input. You would need to type exit to make cmd.exe terminate. You could add this to your code:

p.StandardInput.WriteLine(@"exit");

但是我只是将cmd.exe完全切掉,直接调用python.exe。据我所知,cmd.exe只是增加了额外的复杂性,毫无益处。

But I would just cut out cmd.exe altogether and call python.exe directly. So far as I can see, cmd.exe is just adding extra complexity for absolutely no benefit.

我认为您需要遵循以下原则:

I think you need something along these lines:

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();

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

Also the Python script appears to output to a file rather than to stdout. So when you do p.StandardOutput.ReadToEnd() there will be nothing there.

这篇关于是否可以通过命令提示符从C#运行python代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆