欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#調(diào)用Python腳本的簡單示例

 更新時間:2016年05月17日 11:49:44   作者:MSP_甄心cherish  
這篇文章主要為大家詳細(xì)介紹了C#調(diào)用Python腳本的簡單示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下

IronPython是一種在 .NET及 Mono上的 Python實(shí)現(xiàn),由微軟的 Jim Hugunin所發(fā)起,是一個開源的項(xiàng)目,基于微軟的 DLR引擎。IronPython的在CodePlex上的主頁:http://ironpython.codeplex.com/ 

使用場景:

如果你的小伙伴會寫Python腳本,而且已經(jīng)實(shí)現(xiàn)大部分項(xiàng)目的功能不需要再用C# 實(shí)現(xiàn)?,F(xiàn)在缺少窗體,此時Python+C#的組合就可以完美的結(jié)局問題啦!

示例:
借由IronPython,就可以利用.NET執(zhí)行存儲在Python腳本中的代碼段。下面通過簡單的示例說明如何應(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)求兩個數(shù)的四則運(yùn)算:

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語言引擎的幾個屬性。

<?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ù):

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腳本的簡單方法,希望對大家的學(xué)習(xí)有所幫助。

相關(guān)文章

最新評論