如何将 Python 版本 3 与 .Net 集成

How can I Integrate Python version 3 with .Net

我正在将 Python 脚本集成到 .Net,并且我正在使用 IronPython 包,它可供 Visual Studio 中的 .Net 开发人员使用。我的 Python 代码包含 face_recognition、glob、opencv 等包。我在 运行 这个 python 脚本中遇到错误,尽管简单的 Python 是 运行 in PyCharm。谁能知道我做错了什么?请给我我应该做的答案。

我正在使用的这些包,后来我通过调用它们来使用它:

import face_recognition
import cv2
import glob

video_capture = cv2.VideoCapture(0)

all_images = glob.glob('images/*.jpg')

这是我在 Visual Studio 中的代码:(制作控制台应用程序)

            var py = Python.CreateEngine();

            py.ExecuteFile("C:\Users\Hp\PycharmProjects\final_face\example.py");
            Console.ReadLine();

Visual Studio 我得到的错误是:

Exception thrown: 'Microsoft.Scripting.SyntaxErrorException' in Microsoft.Scripting.dll

The program '[23408] PythonDotNet.exe' has exited with code 0 (0x0).

您遇到错误,因为该功能不是您想要的。

创建一个名为 RunPython.csproj 的新控制台应用程序项目。在主子中,写:

static void Main(string[] args)
{
    var py = Python.CreateRuntime();
    py.ExecuteFile();
}

之后,您可以构建您的项目以生成“.exe”文件。在控制台或 shell 中,写入:

RunPython.exe "C:\Users\Hp\PycharmProjects\final_face\example.py"

您可以访问 this site 查看更多示例。

IronPython 3 尚未准备好投入生产,因此您可以在命令行中执行 Python 脚本并解析输出,而不是使用 IronPython:

  class Program
      {
          static void Main(string[] args)
          {
              Program p = new Program();
              p.butPython();
          }

      public void butPython()
      {
          var hello = "Calling Python...";

          Tuple<String, String> python = GoPython(@"C:\Users\HP\PycharmProjects\final_face\final.py");
          hello = python.Item1; // Show result.
          Console.WriteLine(hello);
          Console.ReadLine();
      }

      public Tuple<String, String> GoPython(string pythonFile, string moreArgs = "")
      {
          ProcessStartInfo PSI = new ProcessStartInfo();
          PSI.FileName = "py.exe";
          PSI.Arguments = string.Format("\"{0}\" {1}", pythonFile, moreArgs);
          PSI.CreateNoWindow = true;
          PSI.UseShellExecute = false;
          PSI.RedirectStandardError = true;
          PSI.RedirectStandardOutput = true;
          using (Process process = Process.Start(PSI))
          using (StreamReader reader = process.StandardOutput)
          {
              string stderr = process.StandardError.ReadToEnd(); // Error(s)!!
              string result = reader.ReadToEnd(); // What we want.
              return new Tuple<String, String>(result, stderr);
          }
      }
  }