Search code examples
c#pythonusingexecute

is there a way to execute a python program using c#?


I want to call my python program and get it executed automatically as it gets called, using c#. I have done uptill opening the program but how to run it and the get the output. It is my final year project kindly help me out.Here is my code:

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)
        {

        }

Solution

  • The following code execute python script that call modules and return result

    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 scripts:

    test.py

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

    module: 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