Sitemap
Damla Yaşar

Damla Yaşar

Developer

How to use Python script in C# project

2 min readSep 17, 2023

I recently solved a problem and would like to share the solution with you briefly, in the hope that it will be helpful.

First option → pythonnet

  1. Open the NuGet Package Manager.
  2. Search for and install ‘pythonnet.’
Press enter or click to view image in full size

3. Navigate to your Local Disk (usually C: drive) and locate the Python programming folder. Find the ‘python311.dll’ file within this folder.

4. Copy the full path to the ‘python311.dll’ file.

5. In your C# code, add ‘using Python.Runtime;’ to import the necessary Python Runtime module.

6. You can now use this module in your ‘Program.cs’ file or wherever you intend to utilize it.”

Get Damla Yaşar’s stories in your inbox

Join Medium for free to get updates from this writer.

This explanation provides a step-by-step guide for solving a problem related to Python integration in a C# application.

Press enter or click to view image in full size

Call the ‘RunScript’ method within any function. Here’s an example of how to invoke the ‘RunScript’ method. Invoke the ‘RunScript’ method from a different class and provide the required parameters.

Second option → IronPython

I spent a long time how to use IronPython in C# project. Ultimately, I found code lines from StackOverflow. I recommend running your Python code using Visual Studio Code separately from Visual Studio. Once you’ve confirmed that your Python code functions correctly, then proceed to integrate IronPython into your C# project. (A piece of advice from a junior developer) 😊

1- Install the IronPython from Nuget.

Press enter or click to view image in full size

2- You don’t need to implement any other methods; this is the most straightforward approach to invoke Python code. The “Name” variable is responsible for invoking the Python script. Use “Python_file” to access functions within the Python script. In this context, “Python_file.main” represents the name of my function, for instance, “def main(parameter):”.

                 try
{
IDictionary<string, object> options = new Dictionary<string, object>();
options["Arguments"] = new[] { @"C:\Program Files (x86)\IronPython 2.7\Lib", "bar" };
//your script path
var name = @"C:\Users\damla\source\repos\fakeksi_backend\WEBAPI\Services\emailconfig\emailconfig.py";
var ipy = IronPython.Hosting.Python.CreateRuntime(options);
dynamic Python_File = ipy.UseFile(name);
//main is my funciton name
Python_File.main(userForRegisterDto.email.ToString());
_usrservice.RegisterActivate(userForRegisterDto.email);
return Ok( registerResult);

}
catch (Exception ex)
{
// Handle the exception (e.g., log it or display an error message).
Console.WriteLine("An error occurred: " + ex.Message);
}

If your Python script functions correctly, you shouldn’t encounter any issues when integrating Python code into your .NET project. I trust this explanation is beneficial.

Happy Coding! :)

--

--