Capture python print statements in C#

拈花ヽ惹草 提交于 2020-05-14 08:58:09

问题


I am writing a C# component which takes an ironpython function as a parameter.

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

C#:

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

Var v returns null for print statements. It works only if I have return(x). Can I capture print statements using ironpython?

Comments and links are appreciated. Also, can just capture it using commandline?


回答1:


This works for me:

using IronPython.Hosting; 
using Microsoft.Scripting.Hosting; //provides scripting abilities comparable to batch files
using System.IO;
using System;
using System.Text;

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()));

Output:

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


来源:https://stackoverflow.com/questions/24456530/capture-python-print-statements-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!