일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 |
- Javascript
- 자바스크립트
- HTML
- Python
- 무료일러스트
- 프로그램
- 쿠팡파트너스
- 파싱
- 워드프레스
- 쿠팡 블로그
- 파이썬
- 아두이노 기초강좌
- Ajax
- ChatGPT
- 자동블로그
- 자동글쓰기
- 쿠팡자동포스팅
- 웹
- 그누보드
- cocos2d-x
- 챗지피티
- 아두이노 초보
- 자동포스팅
- 아두이노
- php
- Php공부
- c#
- 아두이노 강좌
- 쿠파스
- flex
- Today
- Total
플밍
c#에서 파이썬 호출하기 본문
IronPython 이라는 모듈을 사용하면 C#에서 파이썬을 호출하여 결과를 받고 또는 값을 세팅할 수 있습니다.
아래는 C#의 Form.cs 에서 파이썬 test.py 를 호출하여 World 클래스를 실행한 결과입니다.
python3.4 와 ironpython3 를 사용하였습니다.
#ads_1
<< 파이썬 >>
- 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