By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
463,048 Members | 452 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

Two ways to run Python programs from C#

kudos
Expert 100+
P: 127
Some time ago we created an example of how you could use Python from C, both as a separate process and how you
could embed it and run it as part of your C program. Then we realised; perhaps people don't write C programs anymore,so we made the same example in Java. After looking at the bytes.com forum, we started to suspect that perhaps people use C# instead of Java and C.

So here we close the loop and present a C# version!

Installation

We use a Windows 7 computer, with python 2.7 installed. Since we are going to call Python from the command line,
add the path to this Python installation.

Normally, the Python installation is placed in:

C:\Python27

Then to make Python accessible from the command line, we go to control panel, system, advanced system setting and click on this. At the bottom of
this there is going to be an "Environment Variable" button. Click on this, and locate a variable named "Path". If it
isn't there make it, and add C:\Python27. If "Path" is present, we can put C:\Python27 first, but make sure that it ends with a ";"

In our Windows 7, a Visual Studio 10 Express is installed. If such a tool is not present, download and install it.

Process approach

Our idea is the following; We define the Python program in this as a string. This program is going to do two things; Take two numbers from the command line, then add the numbers together and print them out to screen.

The program below will first save the python program to disk (from C#), then it will be executed Python from C# as a process where the program we just saved as a file will be executed.

Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Diagnostics; // Process
  6. using System.IO; // StreamWriter
  7. namespace ConsoleApplication1
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.             // the python program as a string. Note '@' which allow us to have a multiline string
  14.             String prg = @"import sys
  15. x = int(sys.argv[1])
  16. y = int(sys.argv[2])
  17. print x+y";
  18.             StreamWriter sw = new StreamWriter("c:\\kudos\\test2.py");
  19.             sw.Write(prg); // write this program to a file
  20.             sw.Close();
  21.  
  22.             int a = 2;
  23.             int b = 2;
  24.  
  25.             Process p = new Process(); // create process (i.e., the python program
  26.             p.StartInfo.FileName = "python.exe";
  27.             p.StartInfo.RedirectStandardOutput = true;
  28.             p.StartInfo.UseShellExecute = false; // make sure we can read the output from stdout
  29.             p.StartInfo.Arguments = "c:\\kudos\\test2.py "+a+" "+b; // start the python program with two parameters
  30.             p.Start(); // start the process (the python program)
  31.             StreamReader s = p.StandardOutput; 
  32.             String output = s.ReadToEnd();
  33.             string []r = output.Split(new char[]{' '}); // get the parameter
  34.             Console.WriteLine(r[0]);
  35.             p.WaitForExit();
  36.  
  37.             Console.ReadLine(); // wait for a key press
  38.         }
  39.     }
  40. }
  41.  
IronPython approach

There is a cool project which is called IronPython. Just like Jython, which we discussed in the previous article, this is a version of Python that is a part of .net.

Download it from here:

http://ironpython.net/

Install it, and remember the directory where it was installed (which on my computer is : C:\Program Files\IronPython 2.7).

Start up a fresh Console application in Visual Studio, right click on the project to the right and select "Add reference...".

Add all the .dll files in the IronPython directory.

Now you are ready to create strings in C# that is Python programs, execute them in IronPython and basically remove the need for external programs, temporary files and processes. Compared to the Java and the C example, this is kind of simple.

Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using IronPython.Hosting; // make us use Python
  6.  
  7. namespace ConsoleApplication2
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.  
  14.             int a = 1;
  15.             int b = 2;
  16.  
  17.             Microsoft.Scripting.Hosting.ScriptEngine py = Python.CreateEngine(); // allow us to run ironpython programs
  18.             Microsoft.Scripting.Hosting.ScriptScope s = py.CreateScope(); // you need this to get the variables
  19.             py.Execute("x = "+a+"+"+b,s); // this is your python program
  20.             Console.WriteLine(s.GetVariable("x")); // get the variable from the python program
  21.             Console.ReadLine(); // wait for the user to press a button
  22.         }
  23.     }
  24. }
  25.  
Execution time wise, IronPython seems to be a bit slower than using the process approach. But then again, if we are looking at the IronPython web page, the last update to IronPython seems to be over a year ago!
Aug 4 '13 #1
Share this Article
Share on Google+
1 Comment

P: 1
How will the process know to start c:\\kudos\\test2.py with parameters a and b??
Sep 19 '18 #2