這個工作對我來說:
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
的[?我怎樣才能重定向IronPython的在C#標準輸出(可能重複http://stackoverflow.com/questions/3055002/how-can-i-redirect-the-stdout-of-ironpython-in-c) –
如果我有「sys.stdout」,上面的鏈接可以工作。我的腳本只有打印命令? – user2801184
默認情況下,print語句使用'sys.stdout'。 (也參見http://stackoverflow.com/a/3263763/539465) –