我正试图通过ironpython在一个c#项目中嵌入speedtest-cli python脚本。但我无法从ironpython获得任何输出。 Visual Studio 2015社区+ ironpython 2.7。
到目前为止,这是我的一段代码:
private void button2_Click(object sender, EventArgs e)
{
String path = @"C:\test-cli.py";
var source = File.ReadAllText(path);
ScriptEngine py = Python.CreateEngine();
ScriptScope scope = py.CreateScope();
var paths = py.GetSearchPaths();
paths.Add(@"C:\packages\IronPython.StdLib.2.7.5\content\Lib");
py.SetSearchPaths(paths);
try
{
py.Execute(source);
}
catch (Exception ex)
{
Console.WriteLine("Something weird happened...\n" + ex);
Console.ReadKey();
return;
}
}
我试图替换
py.Execute(source);
通过:
var result = py.Execute(source);
result.ToString();
但没有运气......
我设法让它伪工作:
var py = Python.CreateEngine();
py.Runtime.IO.RedirectToConsole();
Console.SetOut(TextWriter.Synchronized(new TextBoxWriter(textBox1)));
string source;
var scope = py.CreateScope();
var reader = new StreamReader(@"c:\speedtest-cli.py");
source = reader.ReadToEnd();
ICollection<string> searchPaths = py.GetSearchPaths();
searchPaths.Add("..\\..");
py.SetSearchPaths(searchPaths);
py.Execute(source);
使用以下覆盖texboxwriter类:
class TextBoxWriter : TextWriter
{
private TextBox _textBox;
public TextBoxWriter(TextBox textbox)
{
_textBox = textbox;
}
public override void Write(char value)
{
base.Write(value);
// When character data is written, append it to the text box.
_textBox.AppendText(value.ToString());
}
public override System.Text.Encoding Encoding
{
get { return System.Text.Encoding.UTF8; }
}
}
但是当python脚本尝试输出到stdout时它会挂起:
sys.stdout.write('.')
我已经放弃了ironpython,不太擅长解析xml数据。 我已经设法使用python 2.7,我已经在Ressources中打包了dll和.py依赖项。我正在将form_load上的包解压缩到用户临时文件夹。