有没有办法用c#执行python程序?

时间:2016-08-13 11:18:23

标签: c# python using execute

我想调用我的python程序,并在使用c#调用它时自动执行它。我已经完成了打开程序但是如何运行它并获得输出。这是我的最后一年项目,请帮助我。这是我的代码:

Process p = new Process();
        ProcessStartInfo pi = new ProcessStartInfo();
        pi.UseShellExecute = true;
        pi.FileName = @"python.exe";
        p.StartInfo = pi;

        try
        {
            p.StandardOutput.ReadToEnd();
        }
        catch (Exception Ex)
        {

        }

1 个答案:

答案 0 :(得分:0)

以下代码执行调用模块并返回结果的python脚本

class Program
{
    static void Main(string[] args)
    {
        RunPython();
        Console.ReadKey();

    }

    static  void RunPython()
    {
        var args = "test.py"; //main python script
        ProcessStartInfo start = new ProcessStartInfo();
        //path to Python program
        start.FileName = @"F:\Python\Python35-32\python.exe";
        start.Arguments = string.Format("{0} ",  args);
        //very important to use modules and other scripts called by main script
        start.WorkingDirectory = @"f:\labs";
        start.UseShellExecute = false;
        start.RedirectStandardOutput = true;
        using (Process process = Process.Start(start))
        {
            using (StreamReader reader = process.StandardOutput)
            {
                string result = reader.ReadToEnd();
                Console.Write(result);
            }
        }
    }
}

测试脚本:

test.py

import fibo
print ( "Hello, world!")
fibo.fib(1000)

模块:fibo.py

def fib(n):    # write Fibonacci series up to n
   a, b = 0, 1
     while b < n:
      print (b),
      a, b = b, a+b