1

How do I execute and return the results of a python script in c#?

I am trying to run a python script from my controller.

I have python.exe setup in a virtual environment folder created with the virtualenv command.

So just for testing purposes at the moment I would like to just return resulting string from my phython script:

# myscript.py
print "test"

And display that in a view in my asp.net mvc app.

I got the run_cmd function from a related stackoverflow question. I've tried adding the -i option to force interactive mode and calling process.WaitForExit() with no luck.

namespace NpApp.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;

            ViewBag.textResult = run_cmd("-i C:/path/to/virtualenv/myscript.py", "Some Input");

            return View();
        }

        private string run_cmd(string cmd, string args)
        {
            ProcessStartInfo start = new ProcessStartInfo();
            start.FileName = @"C:/path/to/virtualenv/Scripts/python.exe";
            start.CreateNoWindow = true;
            start.Arguments = string.Format("{0} {1}", cmd, args);
            start.UseShellExecute = false;
            start.RedirectStandardOutput = true;
            using (Process process = Process.Start(start))
            {
                using (StreamReader reader = process.StandardOutput)
                {
                    string result = reader.ReadToEnd();
                    //Console.Write(result);
                    process.WaitForExit();
                    return result;
                }
            }
        }
    }
}

It seems like myscript.py never even runs. But I get no errors, just a blank variable in my view.

Edit:

I had tried to simplify the above stuff because I thought it would be easier to explain and get an answer. Eventually I do need to use a package called "nameparser" and store the result of passed name argument into a database. But if I can just get the run_cmd to return a string I think I can take care of the rest of it. This is why I think the rest api and IronPython mentioned in the comments may not work for me here.

8
  • You can host python as REST API and invoke that using webclient - myadventuresincoding.wordpress.com/2011/01/02/… -- ignore the word mongodb, it has nothing to do with this, just look at rest api part. Commented Nov 16, 2014 at 6:41
  • Give IronPython a try: codeproject.com/Articles/15579/Call-Ironpython-in-C It's designed for .NET. Commented Nov 16, 2014 at 6:54
  • I don't know python, but you can receive the errorlevel value with ExitCode method, try process.ExitCode Commented Nov 16, 2014 at 7:10
  • Do you see a python.exe process start when running this code? Commented Nov 16, 2014 at 8:28
  • @B.K: I attempted to used IronPython but it seems like it has issues dealing with packages. Plus I got IO errors when running ipy from VisualStudio. Commented Nov 16, 2014 at 12:25

1 Answer 1

2

Ok, I figured out what the issue was thanks to some leads from the comments. Mainly it was the spaces in the path to the python.exe and the myscript.py. Turns out I didn't need -i or process.WaitForExit(). I just moved the python virtual environment into a path without spaces and everything started working. Also made sure that the myscript.py file was executable.

This was really helpful:

string stderr = process.StandardError.ReadToEnd();
string stdout = process.StandardOutput.ReadToEnd();
Debug.WriteLine("STDERR: " + stderr);
Debug.WriteLine("STDOUT: " + stdout);

That shows the python errors and output in the Output pane in Visual Studio.

Sign up to request clarification or add additional context in comments.

Comments

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.