Run python script in c #

I am trying to execute python code in C #. This usually needs to be done with IronPython and after installing PTVS (I am 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 IronPython doesn't seem to recognize some libraries like numpy, pylab or matplotlib. I looked a bit and found some people talking about Enthought Canopy or Anaconda, which I installed without fixing the problem. What to do to solve the problem?

+4
source share
2 answers

To execute a Python script that imports some libraries, such as numpy and pylab, you can do the following:

        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); 
+1
source

, IronPython script . . 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);

, : scriptEngine.SetSearchPaths(searchPaths);. , plot.py , .

, .

0

Source: https://habr.com/ru/post/1615553/


All Articles