說實話,對於我這種小白,在網上找個IronPython找的很費勁,學會操作之后,直接整個隨筆,供新手參考。前提是現在你應該有VS了
(1)找到IronPython的網站
很多人肯定就按照習慣搜索,IronPython下載,然后在各個網站中跳來跳去的,把人都跳煩了。其實非常簡單,直接百度“IronPython”就可以了
進去之后,直接進Download,不跟你多bb
然后選擇其中的穩定版本,這里以2.7.9為例,直接進去
說明一下windows用戶,直接選msi后綴,mac選pkg,當然也得下載IronPython.2.7.9.zip文件,里面包含需要的庫文件。
(2)安裝
下載好msi文件之后,直接下一步下一步安裝即可,可以不安裝到C盤下。
(3)安裝好之后,隨便建一個winform項目,然后隨便加一個button控件,然后將下載的IronPython.2.7.9.zip文件中的net45中的兩個dll復制,如下圖所示
然后將其復制到VS項目的debug中,然后添加引用
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms; 10 using IronPython.Hosting; 11 using Microsoft.Scripting.Hosting; 12 13 namespace TestMyForm 14 { 15 public partial class 測試 : Form 16 { 17 public 測試() 18 { 19 InitializeComponent(); 20 } 21 22 private void 測試_Load(object sender, EventArgs e) 23 { 24 25 } 26 27 private void button1_Click(object sender, EventArgs e) 28 { 29 ScriptRuntime pyRuntime = Python.CreateRuntime(); 30 dynamic obj = pyRuntime.UseFile("F:\\test1.py"); 31 32 string str = obj.Test(); 33 34 MessageBox.Show(str); 35 36 } 37 } 38 }
新手修改起來也很簡單,直接將UseFile中文件路徑修改就可以了。
Python代碼如下
1 def Test(): 2 strOK="First Test" 3 return strOK
運行結果如下圖所示:
不用配置什么路徑,直接用就行,也試過引用import,都可以直接使用