Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Python function from c# (.NET)

Tags:

python

c#

.net

I have Visual Studio 2015 with my main form written in C# and from there I have different classes written in Python (normal Python not Iron Python). How do I call the Python functions from my C# Code?

I know there are multiple topics about this but most of them are too old and some solutions are too difficult or involve to use a middle language like C++.

Here are some links I found useful but didn’t provided with the answer I was exactly searching for:

  • stackoverflow.com/questions/6624503/call-python-from-net

  • stackoverflow.com/questions/27075671/calling-python-from-net-via-c-bridge

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

like image 995
Morganis Avatar asked Feb 17 '16 16:02

Morganis


1 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 its 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();
like image 140
Yar Avatar answered Sep 22 '22 11:09

Yar