在 C# 中执行 python 脚本

execute a python script in C#

我正在尝试在 C# 中执行 python 代码。通常应该使用 IronPython 并在安装 PTVS 之后完成(我使用的是 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);
        }

问题是 IronPython 似乎无法识别某些库,例如 numpy、pylab 或 matplotlib。我稍微看了一下,发现有人在谈论 Enthought Canopy 或 Anaconda,我都安装了它们但没有解决问题。 我应该怎么做才能解决问题?

如果您执行代码,IronPython 只会在当前工作目录中查找脚本。您需要添加更多搜索路径。这是我使用 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 的目录,一切都应该有效。

希望对您有所帮助。

为了执行导入一些库(如 numpy 和 pylab)的 Python 脚本,可以这样做:

        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);