python脚本中import了第三方的包,单独执行运行脚本没问题,C#通过IronPython调用该脚本则报错:no module named…(引用的包名),如何解决?

解决方案 »

  1.   

    将包名如requests2.7中的requests文件夹复制到bin中,不过引用这个包后会出现另外一个报错,求解决
      

  2.   

    现在是只要引用的py文件里有inport,就会报:Microsoft.Scripting.SyntaxErrorException: unexpected token 'from'
     同求解····
      

  3.   

    我怎么感觉俩回复都是楼主的马甲;
    -----------------
    我没做过c#调python,只弄过c/c++调python,也出现过这种问题,好像是python环境未初始化的原因,具体处理办法太久忘了,你可以查一下,我记得这问题网上类似资料蛮多
      

  4.   

    IronPython 默认的搜索路径只有 三个 一个是当前目录[.] 还有两个 貌似分别是 当前目录下的 lib 和 d那个啥的目录
    有些包 是调用不到的 你可以 在你的代码的第一行import sys
    sys.path.append("X:\\python27\\lib");或者嫌麻烦 你可以设置一个环境变量 每次在初始化的时候 去读取环境变量里面的路劲 然后附加到 搜索路径中private ScriptEngine m_engine;
    private ScriptScope m_scope;public 构造器(string strFile) {
    try {
    m_engine = Python.CreateEngine(); #region SetSearchPaths var lstPath = m_engine.GetSearchPaths();
    string strVar = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine);
    if (strVar != null) {
    foreach (var v in strVar.Split(';')) {
    if (v.ToLower().IndexOf("python") != -1)
    lstPath.Add(v);
    }
    }
    strVar = Environment.GetEnvironmentVariable("PYTHON_IMPORT_PATH", EnvironmentVariableTarget.Machine);
    if (strVar != null) {
    foreach (var v in strVar.Split(';')) {
    lstPath.Add(v);
    }
    }
    m_engine.SetSearchPaths(lstPath); #endregion m_scope = m_engine.CreateScope();
    m_engine.CreateScriptSourceFromFile(strFile).Compile().Execute(m_scope);
    } catch (SyntaxErrorException ex) {
    if (m_engine == null) throw ex;
    string strMessage = ex.Message + "\r\n"
    + ex.Severity + " at Line:" + ex.Line + " Col:" + ex.Column + " ErrorCode:" + ex.ErrorCode + "\r\ncode:\r\n    "
    + ex.SourceCode.Split('\n')[ex.Line - 1].Trim();
    throw new Exception(strMessage, ex);
    } catch (Exception ex) {
    if (m_engine == null) throw ex;
    string strMessage = ex.Message + "\r\n\r\n--------IronPython 模块搜索路径:\r\n";
    foreach (var v in m_engine.GetSearchPaths())
    strMessage += v + "\r\n";
    strMessage += "--------\r\n";
    strMessage += "若一些模块无法加载 确认此模块在搜索路劲下 若不再可以尝试一下方案\r\n";
    strMessage += "    1.添加系统环境变量名[PYTHON_IMPORT_PATH] 并在其中添加模块路径\r\n";
    strMessage += "    2.在脚本开头写入以下代码\r\n";
    strMessage += "        import sys\r\n";
    strMessage += "        sys.path.append('yourpath')";
    throw new Exception(strMessage, ex);
    }
    }
      

  5.   


    前一段时间用IronPython的时候遇到过这个问题,需要将IronPython安装目录下的Lib文件夹拷贝到你的Release或Debug路径下,应该可以解决此问题