2

我想通过命令提示符从 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>

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

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

谢谢和问候, P.SARAVANAN

4

3 回答 3

5

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.

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

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

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.

于 2012-04-21T07:15:19.550 回答
2

为什么不在您的应用程序中托管 IronPython,然后执行脚本?

http://blogs.msdn.com/b/charlie/archive/2009/10/25/hosting-ironpython-in-ac-4-0-program.aspx

http://www.codeproject.com/Articles/53611/Embedding-IronPython-in-aC-Application

于 2012-04-21T07:11:40.277 回答
0

或使用py2exe实用地将您的 python 脚本转换为 exe 程序。

详细步骤...

  • download and install py2exe.
  • put your main.py input.xml and output.xml in c:\temp\
  • create setup.py and put it in folder above too

setup.py should contain...

from distutils.core import setup
import py2exe

setup(console=['main.py'])

your c# code then can be...

var proc = new Process();
proc.StartInfo.FileName = @"Python.exe";
proc.StartInfo.Arguments = @"setup.py py2exe";
proc.StartInfo.WorkingDirectory = @"C:\temp\";
proc.Start();
proc.WaitForExit();

proc.StartInfo.FileName = @"C:\temp\dist\main.exe";
proc.StartInfo.Arguments = "input.xml output.xml";
proc.Start();
proc.WaitForExit();
于 2012-04-21T07:15:14.033 回答