Call Python function from C # (.NET)

I have Visual Studio 2015 with my main form written in C #, and from there I have different classes written in Python (regular Python, not Iron Python). How can I name Python functions from my C # code?

I know that there are several topics, but most of them are too old, and some solutions are too complex or involve using a middle language such as C ++.

Here are some links that I found useful, but didn't provide the answer I was exactly looking for:

  • stack overflow

  • stack overflow

Is there an easy way or do I still need a workaround? And if I need a workaround, then what is the easiest?

+7
python c #
source share
2 answers

You can call everything through your command line

System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; startInfo.FileName = "cmd.exe"; startInfo.Arguments = "python whatever"; process.StartInfo = startInfo; process.Start(); 

Or even better, just call Python.exe and pass your py files as an argument:

 System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; startInfo.FileName = "Python.exe"; startInfo.Arguments = "yourfile.py"; process.StartInfo = startInfo; process.Start(); 
+3
source share

The recommended way to do this is to use IronPython . There is another answer that talks about using IronPython to access Python code from C #: How do I call a specific method from Python Script in C #?

If IronPython is not a choice, as you mentioned, you can also run the function from the command line and pass the necessary arguments, although for something complicated it can turn into spaghetti. The following is a basic example of running a python function in a module directly from the command line:

 python -c 'import foo; print foo.hello()' 

So, to run above in C #:

 System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; startInfo.FileName = "python.exe"; startInfo.Arguments = "-c import foo; print foo.hello()"; process.StartInfo = startInfo; process.Start(); 

Please note that if you are trying to return the return value back, in this case you will have to print the data to the console and then serialize the output from C # as you wish. This can be potentially problematic if the function outputs something to the console on its own, if you do not filter it, or there is an option to suppress the output from this function.

-2
source share

All Articles