Konstantin Rybakov Konstantin Rybakov - 1 year ago 105
C# Question

Python script in C# application - IO problems

I am trying to embed famous speedtest-cli.py (speedtest.net client) in my C# application, so I could display the output either in the console or in a texbox.

So far I tried following:

class PythonSpeedTest
private String path = @"c:\pythonSpeedTest.py";

public void runPython() {
var py = Python.CreateEngine();
var scope = py.CreateScope();
var paths = py.GetSearchPaths();
paths.Add(@"C:\Program Files (x86)\IronPython 2.7\Lib");
MemoryStream ms = new MemoryStream();
py.Runtime.IO.SetOutput(ms, new StreamWriter(ms));
var output = py.ExecuteFile(path, scope);

catch (Exception ex)
Console.WriteLine("Python collapsed" + ex.Message);
var sr = new StreamReader(ms);
var result = sr.ReadToEnd();

The application seem to run the script, but
1. it doesn't wait until it finishes, and
2. I couldn't make it display any output from python

Ideally I need to be able to wait until the python completes the test; capture and output results into either console or TextBox, or if I could just capture all the output - that would be fantastic.

Thanks for help!

Answer Source

Alright!!! after beating my head of a wall for a couple of days I've finally figured it out. First, I didn't have to set any streams in order to get an output from python. Here is the code:

class testPython
    public void runScript() {
        String path = @"c:\pythonSpeedTest.py";
        var source = System.IO.File.ReadAllText(path);           
        Microsoft.Scripting.Hosting.ScriptEngine py = Python.CreateEngine();
        Microsoft.Scripting.Hosting.ScriptScope scope = py.CreateScope();
        var paths = py.GetSearchPaths();
        paths.Add(@"c:\Program Files (x86)\IronPython 2.7\Lib");
        try { 
        }catch (Exception ex){
            Console.WriteLine("Error occured in python script\n"+ex);

The important thing was to set paths for python engine. The main problem was that I've been running the script in canopy pressing play button(sorry I'm quite a noob), but in the script itself I've never got to simply call main(). Once I've added it - the script was nicely executed under my C# application. Getting data will be easy now.

Hope this gonna save someone some time!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download