Running a Compiled Python Script from C# Applications
This article will guide you through running a compiled Python script
(.pyc
file) from a C# application, leveraging the capabilities of both languages.
Introduction
The interoperability between different programming languages enables developers to leverage the best features of each language. One such powerful combination is using Python and C# together.
Prerequisites
- Python Installation: Ensure Python is installed on your machine and that
the Python executable is accessible via the system’s
PATH
. You can download Python from the official Python website. - C# Development Environment: You’ll need an environment for writing and running C# code. Visual Studio is a popular choice, but you can use any editor or IDE of your choice.
A Python Script
In order to keep it simple, we will be using the following Python script:
|
|
Save the file as greeter.py
to follow along.
Before running a Python script from C#, you would typically compile it into a
.pyc
file. Here’s how you can compile your Python script:
- Open a terminal or command prompt.
- Run the following command:
|
|
This command will generate a directory named __pycache__
containing the
compiled .pyc
file. In our case:
|
|
C# Application
We start off by creating a console
application using the dotnet
CLI:
|
|
Next, we add the pythonnet package to the project:
|
|
Update the Program.cs
file with the code below to run the compiled (.pyc
)
Python script (greeter.py
):
|
|
Detailed Explanation
Python.Runtime
Initialization:- You must set
Runtime.PythonDLL
property orPYTHONNET_PYDLL
environment variable starting with version 3.0, otherwise you will receiveBadPythonDllException
upon callingInitialize
. - You can read more about the same in their documentation.
- You must set
- Initialize Python Engine:
PythonEngine.Initialize()
: This initializes the Python engine, making Python functionalities available within the C# environment.
- Using Python with GIL:
using (Py.GIL())
: Ensures that the Global Interpreter Lock (GIL) is acquired, which is necessary for thread-safety when interacting with Python objects.
- Modifying Python Path:
dynamic sys = Py.Import("sys")
andsys.path.append("path")
: Adds the__pycache__
directory to the Python path. This is where the compiled.pyc
file resides.
- Import and Execute:
dynamic greeter = Py.Import("greeter")
: Imports the compiled Python script.string result = greeter.Greet("Alice")
: Calls the Greet function from the imported script and prints the result.
- Clean Up:
AppContext.SetSwitch("System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization", true)
: Ensures proper serialization. You can learn more about it in this GitHub issue.PythonEngine.Shutdown()
: Properly shuts down the Python engine to clean up resources.
Running the Application
- Ensure that you have saved the code changes in
Program.cs
. - Open your terminal and navigate to the directory containing
Program.cs
- Run the application using
dotnet run
:
|
|
This will execute the Python script and print the output to the console.
Conclusion
Using Python.NET simplifies the process of integrating Python with C#. You can leverage the capabilities of Python directly from your C# applications, making it possible to use Python’s extensive libraries and simplicity alongside C#’s strong performance and robust framework.
I hope this helps you get started with running compiled Python scripts from C# applications smoothly.