473,383 Members | 1,748 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,383 developers and data experts.

Two ways to run Python programs from C#

kudos
127 Expert 100+
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
1 67326
How will the process know to start c:\\kudos\\test2.py with parameters a and b??
Sep 19 '18 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

220
by: Brandon J. Van Every | last post by:
What's better about Ruby than Python? I'm sure there's something. What is it? This is not a troll. I'm language shopping and I want people's answers. I don't know beans about Ruby or have...
7
by: stormslayer | last post by:
Folks: I've been considering a shift to python. I currently use c++builder (borland) or perl. I do computational models / statistics programming, and was interested in python b/c it a. has...
6
by: Cameron Laird | last post by:
QOTW: "... why does Microsoft try so hard to protect its sources?" "To avoid embarrassment." -- Peter Maas and Grant Edwards http://groups.google.com/groups?frame=left&th=9a599152d8b23b54 ...
31
by: surfunbear | last post by:
I've read some posts on Perl versus Python and studied a bit of my Python book. I'm a software engineer, familiar with C++ objected oriented development, but have been using Perl because it is...
68
by: Lad | last post by:
Is anyone capable of providing Python advantages over PHP if there are any? Cheers, L.
26
by: Christoph Zwerschke | last post by:
You will often hear that for reasons of fault minimization, you should use a programming language with strict typing: http://turing.une.edu.au/~comp284/Lectures/Lecture_18/lecture/node1.html I...
34
by: nicolasfr | last post by:
Hi, I am a bit disapointed with the current Python online documentation. I have read many messages of people complaining about the documentation, it's lack of examples and the use of complicated...
9
by: J. Peng | last post by:
I just thought python's way of assigning value to a variable is really different to other language like C,perl. :) Below two ways (python and perl) are called "pass by reference", but they get...
0
by: david khan | last post by:
Hello, can anybody convert python code that read openstreetmap xml file from http://github.com/rory/python-osm/blob/master/pyosm.py i try to translate but with the lack of knowledge of python ,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.