C#调用IronPython执行Python代码时如何正确导入os、pandas等库
问题根源
你遇到的No module named os报错是因为IronPython运行时默认没有加载自身的标准库搜索路径,第三方库无法导入则是因为IronPython对CPython生态的C扩展类库兼容度有限。
修复步骤
1. 配置IronPython标准库搜索路径
修改你的C#代码,手动指定IronPython的Lib目录路径(替换成你自己设备上的实际路径)和脚本所在目录:
首先确认你已经通过NuGet安装了IronPython和DynamicLanguageRuntime包,然后修改代码如下:
using IronPython.Hosting; using Microsoft.Scripting.Hosting; using System.Collections.Generic; public partial class App : Form { public App() { InitializeComponent(); } static string pythonPath = @"C:\Users\Someone\Documents\main.py"; // 不要直接创建默认Runtime,手动配置路径 static ScriptRuntime python = CreateIronPythonRuntime(); dynamic script = python.UseFile(pythonPath); private static ScriptRuntime CreateIronPythonRuntime() { var options = new Dictionary<string, object>(); // IronPython 3.x需要开启以下配置保证兼容性 options["Frames"] = true; options["FullFrames"] = true; var runtime = Python.CreateRuntime(options); var engine = runtime.GetEngine("py"); var searchPaths = engine.GetSearchPaths(); // 替换为你自己的IronPython安装目录下的Lib文件夹路径 searchPaths.Add(@"C:\Your\IronPython\Install\Path\Lib"); // 添加你的Python脚本所在的目录,避免同目录自定义模块导入失败 searchPaths.Add(@"C:\Users\Someone\Documents"); engine.SetSearchPaths(searchPaths); return runtime; } private void button_Click(object sender, EventArgs e) { string name = "Monica"; // 调用Python函数传参的写法本身没有问题 script.run(name); } }
2. 修复Python脚本语法错误
你当前的Python代码存在两处会导致运行失败的问题,修正后如下:
import os path = os.path.dirname(__file__) def run(name): # 用os.path.join拼接路径避免不同系统的斜杠兼容问题 full_path = os.path.join(path, "demofile.txt") f = open(full_path, "w", encoding="utf-8") # 原write方法参数错误,修正为字符串拼接写法 f.write(f"Hello {name}") f.close()
3. 第三方库(pandas/tensorflow等)安装说明
IronPython仅支持纯Python实现的第三方库,pandas、tensorflow这类依赖CPython C扩展的库无法直接在IronPython环境下运行,有两个替代方案:
- 改用
Python.NET实现C#调用Python逻辑:Python.NET直接调用系统安装的CPython运行时,完全兼容所有CPython生态的第三方库,更适合需要使用数据科学类库的场景 - 如果必须使用IronPython,只能找专门适配IronPython的库版本,或者使用纯Python实现的替代库,安装方式为进入IronPython安装目录的
Scripts文件夹,执行ipy.exe -m pip install 库名即可。
内容的提问来源于stack exchange,提问作者Monica
相关产品推荐
相关产品推荐

