2

I'm trying to embed speedtest-cli python script in a c# project through ironpython. But I can't get any output from ironpython. Visual Studio 2015 Community + ironpython 2.7.

Here's a piece of my code so far:

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;
    }
}

I've tried to replace

py.Execute(source);

By :

var result = py.Execute(source);
result.ToString();

But no luck...

I've managed to get it pseudo-working with:

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

With the following override texboxwriter class:

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; }
        }
    }

But it hangs when the python script try to output to stdout:

sys.stdout.write('.')

I've given up with ironpython, not so good at parsing xml data. I've managed to make it work with python 2.7 which I've packaged in Ressources with dll and .py dependencies. I'm extracting the package on form_load to the user temp folder.

YMB
  • 21
  • 3

0 Answers0