ironpython是一種在 .net及 mono上的 python實(shí)現(xiàn),由微軟的 jim hugunin所發(fā)起,是一個(gè)開源的項(xiàng)目,基于微軟的 dlr引擎。ironpython的在codeplex上的主頁:http://ironpython.codeplex.com/
使用場(chǎng)景:
如果你的小伙伴會(huì)寫python腳本,而且已經(jīng)實(shí)現(xiàn)大部分項(xiàng)目的功能不需要再用c# 實(shí)現(xiàn)。現(xiàn)在缺少窗體,此時(shí)python+c#的組合就可以完美的結(jié)局問題啦!
示例:
借由ironpython,就可以利用.net執(zhí)行存儲(chǔ)在python腳本中的代碼段。下面通過簡(jiǎn)單的示例說明如何應(yīng)用c#調(diào)用python腳本。
1、在vs中新建窗體項(xiàng)目:ironpythondemo
2、vs的菜單中打開“nuget程序包管理器”
3、搜索ironpython程序包并安裝
4、在exe程序所在文件夾下(此例中為".\ironpythondemo\ironpythondemo\bin\debug"),創(chuàng)建python腳本。或?qū)F(xiàn)有的腳本拷貝到該目錄下。python示例腳本實(shí)現(xiàn)求兩個(gè)數(shù)的四則運(yùn)算:
1
2
3
4
5
6
7
8
9
10
11
|
num1 = arg1 num2 = arg2 op = arg3 if op = = 1 : result = num1 + num2 elif op = = 2 : result = num1 - num2 elif op = = 3 : result = num1 * num2 else : result = num1 * 1.0 / num2 |
5、修改工程的配置文件app.config如下:
其中microsoft.scripting節(jié)點(diǎn)中設(shè)置了ironpython語言引擎的幾個(gè)屬性。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<? xml version = "1.0" encoding = "utf-8" ?> < configuration > < configsections > < section name = "microsoft.scripting" type = "microsoft.scripting.hosting.configuration.section, microsoft.scripting" /> </ configsections > < microsoft.scripting > < languages > < language names = "ironpython;python;py" extensions = ".py" displayname = "python" type = "ironpython.runtime.pythoncontext, ironpython" /> </ languages > </ microsoft.scripting > < startup > < supportedruntime version = "v4.0" sku = ".netframework,version=v4.5" /> </ startup > </ configuration > |
6、 繪制窗體如下:
7、編寫計(jì)算的函數(shù):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
private void btncalculate_click( object sender, eventargs e) { scriptruntime scriptruntime = scriptruntime.createfromconfiguration(); scriptengine rbeng = scriptruntime.getengine( "python" ); scriptsource source = rbeng.createscriptsourcefromfile( "ironpythondemo.py" ); / / 設(shè)置腳本文件 scriptscope scope = rbeng.createscope(); try { / / 設(shè)置參數(shù) scope.setvariable( "arg1" ,convert.toint32(txtnum1.text)); scope.setvariable( "arg2" , convert.toint32(txtnum2.text)); scope.setvariable( "arg3" , operation.selectedindex + 1 ); } catch (exception) { messagebox.show( "輸入有誤。" ); } source.execute(scope); labelresult.text = scope.getvariable( "result" ).tostring(); } |
8、編譯運(yùn)行可得計(jì)算結(jié)果(此處未做輸入的檢查)
以上就是c#調(diào)用python腳本的簡(jiǎn)單方法,希望對(duì)大家的學(xué)習(xí)有所幫助。