5

I am trying to execute a python code in C#. Normally it should be done using IronPython and after installing PTVS (I'm using VS 2010).

        var pyEngine = Python.CreateEngine();  
        var pyScope = pyEngine.CreateScope();   

        try
        {
           pyEngine.ExecuteFile("plot.py", pyScope);

        }
        catch (Exception ex)
        {
            Console.WriteLine("There is a problem in your Python code: " + ex.Message);
        }

The problem is that it seems that IronPython doesn't recognize some libraries like numpy, pylab or matplotlib. I took a look a little bit and found some people talking about Enthought Canopy or Anaconda, which i have both installed without fixing the problem. What should I do to get the problem solved?

1
  • You may have to set some search paths. Commented Nov 14, 2015 at 15:20

2 Answers 2

2

In order to execute a Python script which imports some libraries such as numpy and pylab, it is possible to make this:

        string arg = string.Format(@"C:\Users\ayed\Desktop\IronPythonExamples\RunExternalScript\plot.py"); // Path to the Python code
    Process p = new Process();
    p.StartInfo = new ProcessStartInfo(@"D:\WinPython\WinPython-64bit-2.7.5.3\python-2.7.5.amd64\python.exe", arg);
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.CreateNoWindow = true; // Hide the command line window
    p.StartInfo.RedirectStandardOutput = false;
    p.StartInfo.RedirectStandardError = false;
    Process processChild = Process.Start(p.StartInfo); 
Sign up to request clarification or add additional context in comments.

Comments

0

If you execute your code, IronPython will only look for the script in the current working directory. You need to add some more search paths. This is a part of some old integration code in my application using ironpython:

var runtimeSetup = Python.CreateRuntimeSetup(null);
runtimeSetup.DebugMode = false;
runtimeSetup.Options["Frames"] = true;
runtimeSetup.Options["FullFrames"] = true;
var runtime = new ScriptRuntime(runtimeSetup);

var scriptEngine = runtime.GetEngineByTypeName(typeof(PythonContext).AssemblyQualifiedName);

// Set default search paths
ICollection<string> searchPaths = scriptEngine.GetSearchPaths();
searchPaths.Add("\\Scripts\\Python");
scriptEngine.SetSearchPaths(searchPaths);

The trick is to add all paths in this code line: scriptEngine.SetSearchPaths(searchPaths);. If you add the directory which contains plot.py here, all should work.

Hope this helps.

2 Comments

I tried this but strangely nothing has been executed.
Could you add some more details about your project/directory structure? It's hard to find some problems without.

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.