在C#中抛出异常并在IronPython中捕获

时间:2015-08-04 11:15:00

标签: .net exception ironpython

我一直在寻找一个解决方案,我找到的只是“投入Python并捕获C#”的方法。有没有人知道怎么做呢?

理想情况下,我想要一个C#方法并将所有Python代码包装在try / except块中。当C#方法抛出时,我想让Python except抓住它。

我的最后一次尝试:

ScriptEngine pyEngine = Python.CreateEngine(options);
dynamic pyScope = pyEngine.CreateScope();

Action<string> fire = (s) => { throw new Exception(); };
pyScope.Fire = fire;

// ... Load the script...
compiled = source.Compile();
compiled.Execute(pyScope);
// ...

// Somewhere else from a function called by the py script itself 
void calledByPy()
{
    m_pyscope.Fire("s");
}

在Python方面,我的脚本如下:

try:
    calledByPy()
except System.Exception, e:
    print str(e)

我希望看到print str(e)行被调用。

1 个答案:

答案 0 :(得分:1)

我认为麻烦不在你的Python中。我不能完全与所有C#交谈,因为我在IronPython中使用clr.AddReference加载C#程序集,而不是使用ScriptEngine运行解释程序。

这种事情很好:

import clr
import System
clr.AddReference(project_path + '\\bin\\Debug')
from Namespace import CSharpThing

try:
    foo = CSharpThing.DoStuff()  # Multithreaded. Can throw an AggregateException.
except System.AggregateException as ae:
    # I want more information than "One or more exceptions occurred"
    for e in ae.InnerExceptions:
        print(e)
    raise  # Rethrow the original exception, so I get a stack trace to it.