Requirements: Python programming is very popular nowadays, widely used in data analysis and scientific research, large models, deep learning, etc., some model algorithms are written in python, need to use .NET to execute python scripts, pass parameters and obtain results. The online solutions are: process execution, IronPython, pythonnet, and finally pythonnet.
pythonnet-Python.NET
Python.NET is a software package that enables Python programmers to integrate the .NET Universal Language Runtime (CLR) almost seamlessly and provides .NET developers with powerful application scripting tools. It allows Python code to interact with the CLR and can also be used to embed Python into .NET applications.
Address:The hyperlink login is visible.
Prepare the Python environment
This article uses python-3.13.2-embed-amd64 as the running environment, reference:
Python-3.13.2 embed package 64-bit download:The hyperlink login is visible.
Create a new .NET 8 console
Create a new .NET 8 console reference with the following reference:
Since pythonnet will useBinaryFormatterclass, the following exception will be thrown during execution:
Unhandled exception. System.NotSupportedException: BinaryFormatter serialization and deserialization are disabled within this application. SeeThe hyperlink login is visible.for more information. To solve the problem, edit the .csproj node <PropertyGroup> and add the following configuration:
The complete configuration is as follows:
Py.GIL() is an important function in the Python.NET library for obtaining and releasing Global Interpreter Locks (GILs). GIL is a mechanism in the CPython interpreter that ensures that only one thread is executing Python bytecode at any one time. This is important in a multi-threaded environment, especially if Python and .NET code are mixed together.
Python's float type is actually a double-precision float (64 bits), corresponding to C#'s double type.
Execute python code directly
For simple python code, which can be executed directly, the code is as follows:
Call a python function
The code is as follows:
Deploy to Linux environment for testing
Available for normal operation, the tests are as follows:
Reference:
The hyperlink login is visible.
The hyperlink login is visible.
The hyperlink login is visible. |