用C#捕获python打印语句

时间:2014-06-27 16:20:54

标签: c# python ironpython

我正在编写一个C#组件,它将一个ironpython函数作为参数。

    def test():
        x=x+1
        print "Test"

C#:

    var v = engine.Operations.Invoke(scope.GetVariable("test"));

Var vnull语句返回print。仅当我有return(x)时它才有效。我可以使用ironpython捕获打印语句吗?

评论和链接表示赞赏。另外,可以使用命令行捕获它吗?

1 个答案:

答案 0 :(得分:4)

这对我有用:

var script = @"import sys
def test(): 
    print sys.version
    print >> sys.stderr, 'this goes to stderr'
    return 42";

var scriptEngine = Python.CreateEngine();
var scriptScope = scriptEngine.CreateScope();
scriptEngine.Execute(script, scriptScope);
var testFn = scriptScope.GetVariable("test");
var streamOut = new MemoryStream();
var streamErr = new MemoryStream();
scriptEngine.Runtime.IO.SetOutput(streamOut, Encoding.Default);
scriptEngine.Runtime.IO.SetErrorOutput(streamErr, Encoding.Default);
scriptEngine.Operations.Invoke(testFn);
Console.WriteLine("returned: {0}", scriptEngine.Operations.Invoke(testFn));
Console.WriteLine("captured out:\n{0}", Encoding.Default.GetString(streamOut.ToArray()));
Console.WriteLine("captured err:\n{0}", Encoding.Default.GetString(streamErr.ToArray()));

输出:

returned: 42
captured out:
2.7.5b2 (IronPython 2.7.5b2 (2.7.5.0) on .NET 2.0.50727.5477 (64-bit))

captured err:
this goes to stderr