C#使用IronPython庫調(diào)用Python腳本
IronPython是一種在 .NET及 Mono上的 Python實現(xiàn),由微軟的 Jim Hugunin所發(fā)起,是一個開源的項目,基于微軟的 DLR引擎。
IronPython的主頁: IronPython.net /
github站點(diǎn):
方式一:適用于python腳本中不包含第三方模塊的情況
1、執(zhí)行語句
借由IronPython,就可以利用.NET執(zhí)行存儲在Python腳本中的代碼段。下面通過簡單的示例說明如何應(yīng)用C#調(diào)用Python腳本。
1、在VS中新建窗體項目:IronPythonDemo
2、VS的菜單中打開“Nuget程序包管理器”

3、搜索IronPython程序包并安裝

安裝后自動引用如下的DLL

4、在exe程序所在文件夾下創(chuàng)建Python腳本。Python示例腳本實現(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設(shè)置IronPythonDemo.py文件屬性為“復(fù)制到輸出目錄”

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、編寫計算的函數(shù):
ScriptRuntime scriptRuntime = ScriptRuntime.CreateFromConfiguration();
ScriptEngine pyEngine = scriptRuntime.GetEngine("python");
ScriptSource source = pyEngine.CreateScriptSourceFromFile("IronPythonDemo.py");//設(shè)置腳本文件
ScriptScope scope = pyEngine.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)行可得計算結(jié)果(此處未做輸入的檢查)

2、執(zhí)行函數(shù)
IronPythonDemo2.py
def main(arr):
try:
arr = set(arr)
arr = sorted(arr)
arr = arr[0:]
return str(arr)
except Exception as err:
return str(err)c#代碼
ScriptEngine pyEngine = IronPython.Hosting.Python.CreateEngine();//創(chuàng)建Python解釋器對象
dynamic py = pyEngine.ExecuteFile(@"IronPythonDemo2.py");//讀取腳本文件
int[] array = new int[9] { 9, 3, 5, 7, 2, 1, 3, 6, 8 };
string reStr = py.main(array);//調(diào)用腳本文件中對應(yīng)的函數(shù)
MessageBox.Show(reStr);
//或者
ScriptRuntime pyRuntime = IronPython.Hosting.Python.CreateRuntime(); //創(chuàng)建一下運(yùn)行環(huán)境
dynamic obj = pyRuntime.UseFile("IronPythonDemo2.py"); //調(diào)用一個Python文件
int[] array = new int[9] { 9, 3, 5, 7, 2, 1, 3, 6, 8 };
string reStr = obj.main(array);//調(diào)用腳本文件中對應(yīng)的函數(shù)
MessageBox.Show(reStr);方式二:適用于python腳本中包含第三方模塊的情況
C#代碼
using System;
using System.Collections;
using System.Diagnostics;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Process p = new Process();
string path = "reset_ipc.py";//待處理python文件的路徑,本例中放在debug文件夾下
string sArguments = path;
ArrayList arrayList = new ArrayList();
arrayList.Add("com4");
arrayList.Add(57600);
arrayList.Add("password");
foreach (var param in arrayList)//添加參數(shù)
{
sArguments += " " + sigstr;
}
p.StartInfo.FileName = @"D:\Python2\python.exe"; //python2.7的安裝路徑
p.StartInfo.Arguments = sArguments;//python命令的參數(shù)
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();//啟動進(jìn)程
Console.WriteLine("執(zhí)行完畢!");
Console.ReadKey();
}
}
}python腳本
# -*- coding: UTF-8 -*-
import serial
import time
def resetIPC(com, baudrate, password, timeout=0.5):
ser=serial.Serial(com, baudrate, timeout=timeout)
flag=True
try:
ser.close()
ser.open()
ser.write("\n".encode("utf-8"))
time.sleep(1)
ser.write("root\n".encode("utf-8"))
time.sleep(1)
passwordStr="%s\n" % password
ser.write(passwordStr.encode("utf-8"))
time.sleep(1)
ser.write("killall -9 xxx\n".encode("utf-8"))
time.sleep(1)
ser.write("rm /etc/xxx/xxx_user.*\n".encode("utf-8"))
time.sleep(1)
ser.write("reboot\n".encode("utf-8"))
time.sleep(1)
except Exception:
flag=False
finally:
ser.close()
return flag
resetIPC(sys.argv[1], sys.argv[2], sys.argv[3])上面的python腳本實現(xiàn)的是重啟IPC設(shè)備,測試功能成功。
調(diào)用包含第三方模塊的python腳本時,嘗試過使用path.append()方式,調(diào)試有各種問題,最終放棄了,沒有研究。
到此這篇關(guān)于C#使用IronPython庫調(diào)用Python腳本的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#實現(xiàn)創(chuàng)建桌面快捷方式與添加網(wǎng)頁到收藏夾的示例
本文是介紹了c#通過純代碼創(chuàng)建快捷方式與添加網(wǎng)頁到收藏夾,非常具有實用價值,有需要的朋友可以來了解一下。2016-10-10
C#使用DllImport調(diào)用非托管的代碼的方法
C#調(diào)用非托管代碼的方式主要有Com調(diào)用、DllImport方式調(diào)用、加載非托管動態(tài)鏈接庫、直接執(zhí)行機(jī)器碼等方式?,F(xiàn)在介紹一下我自己常用的DllImport方式調(diào)用MSDN中提到的GetShortPathName方法;2013-03-03
DirectoryEntry配置IIS7出現(xiàn)ADSI Error:未知錯誤(0x80005000)
這篇文章主要介紹了DirectoryEntry配置IIS7出現(xiàn)ADSI Error:未知錯誤(0x80005000)的解決辦法2015-09-09
C#中實現(xiàn)在32位、64位系統(tǒng)下自動切換不同的SQLite dll文件
這篇文章主要介紹了C#中實現(xiàn)在32位、64位系統(tǒng)下自動切換不同的SQLite dll文件,本文使用C#代碼實現(xiàn)DLL文件的切換,需要的朋友可以參考下2014-09-09
NumberToUpper數(shù)字轉(zhuǎn)中文詳解
本文介紹NumberToUpper數(shù)字轉(zhuǎn)中文的方法,大家參考使用吧2013-12-12

