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.

3
  • no error message? does this ironpython script work without embedding in ironpython interpeter? Commented Aug 26, 2016 at 13:57
  • No error messages, the script runs in ironpython interpreter. Commented Aug 26, 2016 at 14:10
  • you need to read the result of py.Execute, see answer here: stackoverflow.com/a/5980049/2230844 Commented Aug 26, 2016 at 15:39

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.