본문 바로가기
C#/0x06-ironPyton

c#에서 python 호출하여 사용하기

by SpeeDr00t 2016. 8. 22.
반응형

c#에서 python 호출하여 사용하기

 
1. ironPython 라이브러리 다운로드
 

2. ironPython 설치

3. visual stdio 2015에서 visual c#선택후

   콘솔 응용 프로그램 선택

4. 참조 추가

 - "참조" 선택후 우클릭하여 참조관리자 띄워서 추가

5. program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;


//파이선을 실행하기 위해 추가
using IronPython;
using IronPython.Hosting; 
using IronPython.Runtime;
using IronPython.Modules;


namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            //먼저 참조추가에서 IronPython을 추가하야 한다.

            var engine = IronPython.Hosting.Python.CreateEngine();


            var scope = engine.CreateScope();

            try
            {
                //파이선 프로그램 파일 실행.
                var source = engine.CreateScriptSourceFromFile("simple.py");
                source.Execute(scope);

                // call def HelloWorld() :
                var Fnhelloworld = scope.GetVariable<Func<object>>("HelloWorld");
                Console.WriteLine(Fnhelloworld());

                // call def HelloWorld2(data) :
                var Fnhelloworld2 = scope.GetVariable<Func<object, object>>("HelloWorld2");
                Console.WriteLine(Fnhelloworld2("HelloWorld 2 "));
                
                // call def ListTest() :
                var FnListTest = scope.GetVariable<Func<object>>("ListTest");

                IronPython.Runtime.List r = (IronPython.Runtime.List)FnListTest();

                foreach (string data in r)
                {
                    Console.WriteLine("result: {0}", data);
                }

                // call class MyClass
                var myClass = scope.GetVariable<Func<object, object>>("MyClass");
                var myInstance = myClass("hello");

                Console.WriteLine(engine.Operations.GetMember(myInstance, "value"));

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }


        }
    }
}

 

6.simple.py

def HelloWorld():
    data = 'Hello World C#'
    return data 
 
def HelloWorld2( data ):
    return data 

def ListTest():

    data = []
    data.append('Hello')
    data.append('World')
    data.append('black falcon') 
    return data

class MyClass(object):
    def __init__(self, value):
        self.value = value

 

simple.py 위치(debug 폴더)

 

 

결과

 

 

ConsoleApplication2.zip
다운로드

 

반응형