C# 코드에서 Python Script 실행하는 3가지 방법

  1. Process to execute (https://www.youtube.com/watch?v=g1VWGdHRkHs)
  2. IronPython(nuget package 추가, 아직 IronPython3 없어서 python3 미지원)
  3. pythonnet(DLL 파일 추가하여 진행, nuget package 없음)

 

  • Process to execute (https://www.youtube.com/watch?v=g1VWGdHRkHs)
    1. Install Python
    2. Create a process for Python.exe
    3. Provide Script and arguments
    4. Process configuration
    5. Execute process and get output
    6. Display output
    • 영상에 자세히 나옴.
  • IronPython(nuget package 추가)
    • nubet package 추가(검색 IronPython)
    • Python2 까지 사용가능

      var engine = IronPython.Hosting.Python.CreateEngine();
      var scope = engine.CreateScope();try
      {
      var source = engine.CreateScriptSourceFromFile(@"*py file path*");
      source.Execute(scope);

      var getPythonFuncResult = scope.GetVariables<Func<string>>("*python function*");
      Console.WriteLine("def 실행 테스트 : " + getPythonFuncResult());

      var sum = scope.GetVariables<func<int, int, int>>("sum");
      console.WriteLine(sum(1,2));
      }
      catch(Exception ex)
      {
      Console.WriteLine(ex.Message);
      }
  • pythonnet(DLL 파일 추가, https://nowonbun.tistory.com/690)
    • phthonnet을 사용하기 위해 https://github.com/pythonnet/pythonnet 에서 소스 다운(solution file  : pythonnet.sln)
    • 프로젝트의 프로퍼티에서 configuration및 General의 Conditional compilation symbols 수정 (python 버전에 맞춰 수정 예) python3.7 → PYTHON3;PYTHON37;UCS2), Platform target 수정
    • 빌드 후 나온 dll 파일을 pythonnet을 사용하려는 프로젝트의 Reference Manager에서 추가
    • Python.Runtime namespace 추가.

 

//환경 변수 path 설정

// Python 홈 설정.

PythonEngine.PythonHome = PYTHON_HOME;

// 모듈 패키지 path 설정.

// pip하면 설치되는 패키지 폴더 설정

Path.Combine(PYTHON_HOME, @"Lib\site-packages")

// Python 엔진 초기화

PythonEngine.Initialize();

// Global Interpreter Lock을 취득

using (Py.GIL())

{

// String 식으로 python 식 테스트

PythonEngine.RunSimpleString(@"

import sys;

print('hello world');

print(sys.version);

");

// 개인 패키지 폴더의 py file을 읽는다.

dynamic test = Py.Import("example.test");

// example/test.py의 Calculator 클래스를 선언

dynamic f = test.Calculator(1, 2);

// Calculator의 add함수를 호출

Console.WriteLine(f.add());

}

// python 환경을 종료한다.

PythonEngine.Shutdown();

+ Recent posts