How to call Python code in C#
There are several different ways to call Python code in C#.
A common method is to uselibrary, which allows you to call Python code directly in C#. Another way is to use an external process to call a Python script, for example through
。
Here are two main methods in detail:
1. Use
Install
First, you need to install it. You can install it through the NuGet package manager:
Install-Package
Sample code:
Next, let's see how to use itCall Python code in C#.
using System; using ; namespace CSharpPythonIntegration { class Program { static void Main(string[] args) { // Initialize the Python runtime using (()) { // Load Python module dynamic pyModule = ("your_python_module"); // Call Python functions dynamic result = (args); ($"Result from Python: {result}"); } } } }
Notes:
- Before calling Python code, make sure that the Python runtime environment is correctly installed on the target machine.
- You need to make sure that the paths to Python modules and scripts are correct.
- use
()
to ensure that global interpreter locks (GILs) are handled correctly in C#.
2. Call Python scripts using external processes
If you don't want to use, you can run Python scripts by creating a process.
Sample code:
Here is a simple example that demonstrates how to use itClass to run Python scripts.
using System; using ; namespace CSharpPythonIntegration { class Program { static void Main(string[] args) { string pythonScriptPath = @"C:\path\to\your\"; string pythonExePath = @"C:\Python39\"; // Python interpreter path ProcessStartInfo startInfo = new ProcessStartInfo(pythonExePath, pythonScriptPath) { RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true }; using (Process process = new Process()) { = startInfo; (); // Read the output of Python scripts string output = (); (); ($"Output from Python script: {output}"); } } } }
Notes:
- You need to make sure that the path to the Python interpreter is correct.
- If your Python scripts rely on external modules, make sure that these modules are already installed on the target machine.
- If your Python script needs to enter parameters, you can
ProcessStartInfo
Add the parameter string to the second parameter of the constructor.
Both methods can achieve the goal of calling Python code in C#, butProvides tighter integration, while using external processes is simpler and more direct, suitable for simple calling scenarios.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.