You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用IronPython执行脚本报错:No module named 'config' 求助

解决IronPython执行脚本时"No module named 'config'"的问题

问题背景

执行IronPython脚本时触发错误:No module named 'config',项目文件结构如下:

Root
└── ConfigGenerator
    └── __config_generator.py
└── config.py

__config_generator.py核心代码:

import config

CONFIG = config.Config()

# 其余代码省略

C#调用IronPython的核心代码:

using Microsoft.Scripting.Hosting;
using IronPython.Hosting;
using System;
using System.Windows.Forms;

namespace ProjectName
{
    public partial class MainForm : Form
    {
        private ScriptEngine _engine;

        public MainForm()
        {
            _engine = Python.CreateEngine();
            InitializeComponent();
        }

        private void StartConfigGenerator_Click(object sender, EventArgs e)
        {
            RunScript(@"Q:\Project\Python\Bots\Root\ConfigGenerator\__config_generator.py");
        }

        private void RunScript(string path)
        {
            _engine.ExecuteFile(path);
        }
    }
}

问题原因

IronPython默认将脚本所在目录(即ConfigGenerator)作为模块搜索路径,而config.py位于上级的Root目录,不在默认搜索范围内,因此无法找到该模块。

解决方案

方案1:从C#层面添加搜索路径

修改RunScript方法,将Root目录添加到IronPython的模块搜索路径中:

private void RunScript(string path)
{
    // 获取脚本目录的上级目录(Root目录)
    string rootDir = System.IO.Path.GetDirectoryName(System.IO.Path.GetDirectoryName(path));
    // 获取当前引擎的搜索路径集合
    var searchPaths = _engine.GetSearchPaths();
    // 添加Root目录到搜索路径
    searchPaths.Add(rootDir);
    _engine.SetSearchPaths(searchPaths);
    
    _engine.ExecuteFile(path);
}

方案2:在Python脚本内部修改搜索路径

在__config_generator.py开头添加代码,将Root目录加入Python的搜索路径:

import sys
import os

# 获取当前脚本所在目录的上级目录(Root目录)
root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(root_dir)

# 之后再导入config模块
import config

CONFIG = config.Config()

# 其余代码省略

方案对比

  • 方案1适合多脚本共享上级目录模块的场景,一次配置全局生效;
  • 方案2更灵活,仅针对当前脚本生效,无需修改C#代码。

内容的提问来源于stack exchange,提问作者LOK1game

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 20:52:47