플밍

c#에서 파이썬 호출하기 본문

프로그래밍/PyThon

c#에서 파이썬 호출하기

너구리안주 2015. 12. 20. 18:25


IronPython 이라는 모듈을 사용하면 C#에서 파이썬을 호출하여 결과를 받고 또는 값을 세팅할 수 있습니다.

아래는 C#의 Form.cs 에서 파이썬 test.py 를 호출하여 World 클래스를 실행한 결과입니다.

python3.4 와 ironpython3 를 사용하였습니다.

#ads_1

http://ironpython.net/


<< 파이썬 >>

- test.py -

# -*- coding: utf-8 -*-

class World:

def __init__(self):

self.name = 'AAA'


def hello(self):

print("Hello")


def getName(self):

return self.name


def add(self, a, b):

return (a + b)


def setName(self, name):

self.name = name

return self.name


if __name__ == '__main__':

w = World()

print(w.getName())


#ads_2

<< C# >>

- Form1.cs -

using System;

using System.Collections.Generic;

using System.Windows.Forms;

using IronPython.Hosting;

using Microsoft.Scripting.Hosting;

using System.IO;


namespace pytest

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }


        private void button1_Click(object sender, EventArgs e)

        {

            var engine = Python.CreateEngine();

            ICollection<string> searchPaths = engine.GetSearchPaths();

            searchPaths.Add(@"d:\_PROJECT\test\pytest\pytest\pytest\bin");

            engine.SetSearchPaths(searchPaths);

            

            foreach (string path in searchPaths)

            {

                System.Console.Out.WriteLine(path);

            }

            System.Console.Out.WriteLine();            


            ScriptSource script = engine.CreateScriptSourceFromFile("test.py");

            ScriptScope scope = engine.CreateScope();

            script.Execute(scope);


            dynamic w = scope.GetVariable("World")();            

            w.hello();

            System.Console.Out.WriteLine("Your Name is " + w.getName());

            System.Console.Out.WriteLine("5 + 10 = " + w.add(5, 10));

            System.Console.Out.WriteLine("Your Name is " + w.setName("C#"));

            System.Console.Out.WriteLine("Your Name is " + w.getName());

        }

    }

}



<< 결과 >>

Hello   //hello();

Your Name is AAA  //getName();

5 + 10 = 15  //add(5, 10);

Your Name is C#  //setName("C#"); 실행 후 getName();

#ads_3

Comments