7

I have some python code that does a certain task. I need to call this code from C# without converting the python file as an .exe, since the whole application is built on C#.

How can I do this?

denfromufa
  • 5,610
  • 13
  • 81
  • 138
Raj
  • 440
  • 2
  • 6
  • 22

3 Answers3

6

If your python code can be executed via IronPython then this is definitely the way to go - it offers the best interop and means that you will be able to use .Net objects in your scripts.

There are many ways to invoke IronPython scripts from C# ranging from compiling the script up as an executable to executing a single script file or event dynamically executing expressions as they are typed in by the user - check the documentation and post another question if you are still haivng problems.

If your script is a CPython script and can't be adapted to work with IronPython then your options are more limited. I believe that some CPython / C# interop exists, but I couldn't find it after a quick Google search. The best thing I can think of would be to just invoke the script directly using python.exe and the Process class.

Justin
  • 84,773
  • 49
  • 224
  • 367
5

Have a look at IronPython.

Based on your answer and comments, I believe that the best thing you can do is to embed IronPython in your application. As always, there is a relevant SO question about this. As Kragen said, it is important not to rely on a CPython module.

Community
  • 1
  • 1
kgiannakakis
  • 103,016
  • 27
  • 158
  • 194
  • It converts the python code into an .exe file and then it is called by the c#. i want python program directly called by c# code. – Raj Apr 08 '11 at 07:06
  • @user692856 You can always compile the python code into a DLL instead of an EXE using IronPython, then reference that from your C# project. – Bradley Smith Apr 08 '11 at 07:19
1

Process.Start is what you're after. It allows you to call another program, passing it arguments.

Josh Smeaton
  • 47,939
  • 24
  • 129
  • 164