IronPython:改变SourceCodeKind.InteractiveCode的行为

时间:2014-02-12 19:38:18

标签: c# ironpython

我可以用C#执行IronPython:

ScriptSource Source = PyEngine.CreateScriptSourceFromString(Code, SourceCodeKind.InteractiveCode);
CompiledCode Compiled = Source.Compile();
Compiled.Execute(PyScope);

这意味着我可以执行A=1然后A。然后输出1

有没有办法可以覆盖此行为,因此A会被重定向到C#函数,比如说CustomPrinter之前打印?我知道https://stackoverflow.com/a/13871861/1447657可以“重载”print函数,但我觉得应该有更好的方法。

修改1

感谢您的回答,但我对目标略显不清楚。

我知道我可以使用PyEngine.Runtime.IO.SetOutput(stream, encoding)重定向输出,但我希望在将输出值转换为字符串之前检索输出值。因此,如果收到A=[1,2,3] IronPython.Runtime.List而不是string,则会收到。

我不确定如果不改变IronPython源代码或使用Regex在A函数

中自行包装变量(如CustomPrinter.Write),这是否可行

2 个答案:

答案 0 :(得分:2)

您可以PyEngine.Runtime.IO.SetOutput(stream, encoding)stdout的内容指向自定​​义流(另请参阅.SetErrorOutput stderr.SetInput stdin })。

答案 1 :(得分:0)

您可以实现文件对象(在这种情况下,您只需要写入方法接受字符串)并将其分配给sys.stdout。

public class PythonFile {
    public void write(string s) {
    }
}

以后:

PyEngine.GetSysModule().SetVariable("stdout", new PythonFile());
相关问题