Language - C#/C#(문법)

C# - Visual Studio Python 연동 - 1

KimTory 2021. 11. 10. 13:03

추후 실무 간, Python + C# 연동해서 PJT를 진행 할 날이 올 것 같아 미리 포스팅해서 내용 정리 해보려고 합니다!

설치 및 기본 예제 코드는 StackOverFlow - GitHub 에서 주로 참고해서 블로그 작성했습니다.

 

▶ Language : C#, Python

▶ IDE         : Visual Studio 2017, Visual Studio Code

 

 

▶ 설치 방법

  • IronPython 설치

도구 - NuGet 패키지 관리 - 솔루션용 NuGet 패키지 관리

  • NuGet 패키지 관리

IronPython 2.7.11 Ver 설치
참조 확인
test.py / code

  • C# - Python 연동 Code
using System;

using IronPython;
using IronPython.Modules;
using IronPython.Hosting;
using IronPython.Runtime;

// Python Engine Create
var engine = IronPython.Hosting.Python.CreateEngine();
// Python Scope Create
var scope = engine.CreateScope();

try
{
    // Python File Read
    // test.py 실제 경로
    var source = engine.CreateScriptSourceFromFile("test.py");
    // source(Python File Reading) - Scope Input - Run
    source.Execute(scope);

    // Function return
    var getPythonFunc = scope.GetVariable<Func<string>>("getHello"); // test.py Reading 시, Print(~)
    Console.WriteLine("def 실행 테스트 : " + getPythonFunc()); // result - Hello

    // int 매개 변수 2ea, return type (int)
    var sum = scope.GetVariable<Func<int, int, int>>("sum"); 
    Console.WriteLine("def 실행 테스트 : " + sum(2, 3)); // result - 5

    // class return
    var getPython = scope.GetVariable("getObject")(1, 2);
    // getObject - sum func run
    Console.WriteLine("def 실행 테스트 : " + getPython.sum());  // result - 3
}
catch(Exception ex)
{
    Console.WriteLine(ex.Message);
}