473,480 Members | 2,157 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Two ways to run Python programs from C#

kudos
127 Recognized Expert New Member
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 67367
rakshabnayak
1 New Member
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
18791
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
2051
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
1897
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
4719
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
5768
by: Lad | last post by:
Is anyone capable of providing Python advantages over PHP if there are any? Cheers, L.
26
3179
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
2875
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
2139
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
2137
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
7055
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
6920
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7106
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6760
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
4501
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3013
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3004
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1311
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
206
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

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.