473,606 Members | 2,171 Online
Bytes | Software Development & Data Engineering Community
+ 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 "Environmen t 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\IronPytho n 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 67400
rakshabnayak
1 New Member
How will the process know to start c:\\kudos\\test 2.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
18960
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 any preconceived ideas about it. I have noticed, however, that every programmer I talk to who's aware of Python is also talking about Ruby. So it seems that Ruby has the potential to compete with and displace Python. I'm curious on what basis it...
7
2060
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 a library that connects to the R stats package b. has code that seems way more readable than anything else There is, however, at least for my work, a hard constraint. Execution
6
1918
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 "Sufficiently advanced cluelessness is indistinguishable from malice." -- Alex Martelli 2.4 is final, buildable under Windows in at least a couple of ways, improved, ...
31
4760
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 great for pattern matching, text processing, and automated testing. Our company is really fixated on risk managnemt and the only way I can do enough testing without working overtime (which some people have ended up doing) is by automating my...
68
5827
by: Lad | last post by:
Is anyone capable of providing Python advantages over PHP if there are any? Cheers, L.
26
3215
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 just came across a funny example in which the opposite is the case. The following is a binary search algorithm in Java. It searches a value in an ordered array a of ints: public static int binarySearch(int a, int key) {
34
2905
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 sentences that you need to read 10 times before understanding what it means. That's why I have started a collaborative project to make a user contributed Python documentation. The wiki is online here: http://www.pythondocs.info
9
2149
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 different results. Yes I'm reading 'Core python programming', I know what happened, but just a little confused about it. $ cat t1.py def test(x):
0
2141
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 , never get it done. Even approximate conversion that will be greate. If the whole file is too much , if someone can translate a couple of class from this file like class Node(object): class Way(object): that will be great as well, and i...
0
8015
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8430
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8094
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8305
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
5966
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5465
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3930
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3977
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2448
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 we have to send another system

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.