0

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

        }
  • Possible duplicate of [run a python script from c#](http://stackoverflow.com/questions/11779143/run-a-python-script-from-c-sharp) – M.Hassan Aug 13 '16 at 12:57
  • I've tried this one and much more but all leave me helpless with the exception "no module named __future__" kindly guide me in this if any idea. thanks anyways – Rida Akhtar Aug 14 '16 at 16:26
  • Define the working directory, pi.WorkingDirectory = @"your_working_directory_to_main_python_script". i used http://stackoverflow.com/a/11779234/3142139 in the same link with minor change, i will post my code sooner, and it's working :) – M.Hassan Aug 14 '16 at 17:11
  • thanks alot :) this worked for me. – Rida Akhtar Aug 15 '16 at 10:26
  • Welcome. Happy that you resolved your problem. If my answer satisfy you, mark it as accepted answer. – M.Hassan Aug 15 '16 at 10:59

1 Answers1

0

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
M.Hassan
  • 10,282
  • 5
  • 65
  • 84