[C# 문법] C# 에서 IronPython 이용하여 Python 연동

참조


목적

  • IronPython3 라이브러리를 사용하여 C#에서 Python 사용 가능한지 POC 진행합니다.

IronPython 개요

  • IronPython은 .NET에 탁원한 추가 기능으로 Python 개발자에게 .NET의 강력한 기능을 제공하는 오픈소스 입니다.
  • 기존 .NET 개발자는 새로운 애플리케이션을 처음부터 포함, 테스트 또는 작성하기 위한 빠르고 표현력이 뛰어난 스크립팅 언어로 IronPython을 사용할 수도 있습니다.

최신 정보

  • IronPython 공식 홈페이지에서 가장 최신에 발표된 버전은 IronPython-3.4.0-alpha 버전입니다.

개발 환경

  • .NET Version : .NET 6
  • 개발 도구 : Visual Studio 2022

사용 NuGet Package

  • 현재 기준 가장 최신 버전의 IronPython NuGet Package 는 IronPython-3.4.0-alpha 버전입니다.
  • 참고로 해당 버전은 테스트 버전 입니다.

테스트 파이썬 파일 내용

def getPythonFunc():
    return "hello"

def sum(a,b):
    return a+b

print('hello iron python')

예제 코드

var eng = IronPython.Hosting.Python.CreateEngine();
var scope = eng.CreateScope();
var paths = eng.GetSearchPaths();

// Python 경로 설정
paths.Add(@"C:\Users\bh.cho\AppData\Local\Programs\Python\Python310");
paths.Add(@"C:\Users\bh.cho\AppData\Local\Programs\Python\Python310\DLLs");
paths.Add(@"C:\Users\bh.cho\AppData\Local\Programs\Python\Python310\Lib");
paths.Add(@"C:\Users\bh.cho\AppData\Local\Programs\Python\Python310\Lib\site-packages");
paths.Add(@"C:\Users\bh.cho\AppData\Local\Programs\Python\Python310\Lib\site-packages\tensorflow_datasets");
paths.Add(@"C:\Users\bh.cho\AppData\Local\Programs\Python\Python310\Lib\site-packages\tensorflow_metadata");
paths.Add(@"C:\Users\bh.cho\AppData\Local\Programs\Python\Python310\Lib\site-packages\tensorflow_serving");

// 실행 시킬 Python 파일 경로
var source = eng.CreateScriptSourceFromFile(@"C:\Users\bh.cho\OneDrive\바탕 화면\IronPythonTest\test\bin\Debug\Calculate.py");

// 파이썬 파일 실행
source.Execute(scope);

var getPythonFuncResult = scope.GetVariable < Func<int, int, int>>("sum");
Console.WriteLine($"def 실행 테스트 : " + getPythonFuncResult(1, 2));

실행 결과

hello iron python
def 실행 테스트 : 3

728x90

이 글을 공유하기

댓글

Designed by JB FACTORY