gpt4 book ai didi

c# - 在 C# 中捕获 python 打印语句

转载 作者:太空宇宙 更新时间:2023-11-03 20:04:42 25 4
gpt4 key购买 nike

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

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

C#:

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

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

欢迎评论和链接。另外,是否可以使用命令行捕获它?

最佳答案

这对我有用:

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

输出:

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

关于c# - 在 C# 中捕获 python 打印语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24456530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com