在 RedHat 系统(RHEL 7/8/9)中安装 pythonnet 和 .NET Core 的完整指南

​1. 安装 .NET Core SDK​

​RHEL 8/9(推荐)​

bash

bash 复制代码
# 添加微软仓库
sudo rpm -Uvh https://packages.microsoft.com/config/rhel/8/packages-microsoft-prod.rpm

# 安装 .NET 8 SDK(包含运行时)
sudo dnf install -y dotnet-sdk-8.0

# 验证安装
dotnet --info
​RHEL 7​

bash

bash 复制代码
sudo rpm -Uvh https://packages.microsoft.com/config/rhel/7/packages-microsoft-prod.rpm
sudo yum install -y dotnet-sdk-8.0

​2. 安装 Python 3.8+​

bash

bash 复制代码
# RHEL 8/9 默认有Python 3.9+
sudo dnf install -y python3 python3-devel

# RHEL 7 需要启用SCL仓库
sudo yum install -y centos-release-scl
sudo yum install -y rh-python38 python38-devel
scl enable rh-python38 bash  # 临时启用Python 3.8

​3. 安装 pythonnet​

​方法1:通过 pip 安装(推荐)​

bash

bash 复制代码
# 安装编译依赖
sudo dnf install -y gcc glibc-devel python3-devel

# 安装 pythonnet
pip3 install pythonnet --pre  # 必须使用 --pre 安装预览版以支持 .NET Core
​方法2:源码编译安装​

bash

bash 复制代码
git clone https://github.com/pythonnet/pythonnet
cd pythonnet
pip3 install .

​4. 配置环境变量​

bash

bash 复制代码
# 永久生效(添加到 ~/.bashrc)
echo 'export PYTHONNET_PYDLL=libpython3.9.so.1.0' >> ~/.bashrc  # 根据实际Python版本修改
echo 'export PYTHONNET_RUNTIME=coreclr' >> ~/.bashrc  # 强制使用 .NET Core
source ~/.bashrc

​5. 验证安装​

python

bash 复制代码
import clr
from System import DateTime
print(DateTime.Now)

正常应输出当前时间,如:

markdown

bash 复制代码
2023-11-20 14:30:00

​6. 常见问题解决​

​问题1:找不到 libpython

bash

bash 复制代码
# 查找 libpython 路径
find /usr -name 'libpython*.so*'

# 手动指定路径(例如Python 3.8)
export PYTHONNET_PYDLL=/opt/rh/rh-python38/root/usr/lib64/libpython3.8.so.1.0
​问题2:pythonnet 仍尝试使用 Mono​

bash

bash 复制代码
# 强制使用 .NET Core
export PYTHONNET_RUNTIME=coreclr
​问题3:GLIBC 版本过低​

bash

bash 复制代码
# 升级到 RHEL 8+ 或使用独立部署
dotnet publish --self-contained -r linux-x64

​7. 完整卸载​

bash

bash 复制代码
# 卸载 pythonnet
pip3 uninstall pythonnet

# 卸载 .NET Core
sudo dnf remove -y dotnet-*
sudo rm -rf /usr/share/dotnet

​版本兼容性参考​

组件 RHEL 7 支持版本 RHEL 8/9 支持版本
.NET Core 6.0(需手动安装) 6.0/7.0/8.0
pythonnet ≥3.0.0(需源码编译) ≥3.0.0
Python 3.6-3.8(SCL仓库) 3.9+

建议新项目使用 ​​RHEL 8/9 + .NET 8 + pythonnet 3.0​​ 组合。

相关推荐
时光追逐者1 天前
C#/.NET/.NET Core技术前沿周刊 | 第 58 期(2025年10.13-10.19)
微软·开源·c#·.net·.netcore
weixin_3798809212 天前
.Net Core WebApi集成Swagger
java·服务器·.netcore
The Future is mine14 天前
.Net Core 在Linux系统下创建服务
linux·运维·.netcore
*长铗归来*15 天前
ASP.NET Core Web API 中控制器操作的返回类型及Swagger
后端·c#·asp.net·.netcore
IDOlaoluo15 天前
VS2017 安装 .NET Core 2.2 SDK 教程(包括 dotnet-sdk-2.2.108-win-x64.exe 安装步骤)
.netcore
csdn_aspnet22 天前
使用 Entity Framework Code First 方法创建 ASP.NET Core 5.0 Web API
.netcore·webapi
小先生81222 天前
.NET Core项目中 Serilog日志文件配置
c#·.netcore
爱吃香蕉的阿豪22 天前
.NET Core 中 System.Text.Json 与 Newtonsoft.Json 深度对比:用法、性能与场景选型
数据库·json·.netcore
csdn_aspnet22 天前
ASP.NET Core 10.0 的主要变化
.netcore
csdn_aspnet25 天前
在 C# .NETCore 中使用 MongoDB(第 1 部分):驱动程序基础知识和插入文档
mongodb·.netcore