C#使用IronPython庫調(diào)用Python腳本
IronPython是一種在 .NET及 Mono上的 Python實(shí)現(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示例腳本實(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設(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腳本實(shí)現(xiàn)的是重啟IPC設(shè)備,測試功能成功。
調(diào)用包含第三方模塊的python腳本時,嘗試過使用path.append()方式,調(diào)試有各種問題,最終放棄了,沒有研究。
到此這篇關(guān)于C#使用IronPython庫調(diào)用Python腳本的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#中使用Cache框架快速實(shí)現(xiàn)Cache操作
這篇文章介紹了C#中使用Cache框架快速實(shí)現(xiàn)Cache操作的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06
C#啟動和停止windows服務(wù)的實(shí)例代碼
這篇文章介紹了C#啟動和停止windows服務(wù)的實(shí)例代碼,有需要的朋友可以參考一下2013-09-09
C# Winform中實(shí)現(xiàn)主窗口打開登錄窗口關(guān)閉的方法
這篇文章主要介紹了C# Winform中實(shí)現(xiàn)主窗口打開登錄窗口關(guān)閉的方法,這在需要用戶名密碼的軟件項目中是必用的一個技巧,要的朋友可以參考下2014-08-08
C#將Word或Excel文檔轉(zhuǎn)換為Html文件
這篇文章介紹了C#將Word或Excel文檔轉(zhuǎn)換為Html文件的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06
用C#實(shí)現(xiàn)啟動另一程序的方法實(shí)例
一段實(shí)例代碼,程序的目的是使用C#實(shí)現(xiàn)啟動另一程序的方法。技術(shù)總監(jiān)給出了我們這樣一個有效的啟動程序的有效方法,現(xiàn)在和大家分享下2013-07-07
C#窗體實(shí)現(xiàn)點(diǎn)餐系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了C#窗體實(shí)現(xiàn)點(diǎn)餐系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-08-08
C#如何在WinForm中打開Excel文件,或打開Excel應(yīng)用顯示數(shù)據(jù)
這篇文章詳細(xì)介紹了如何在WinForm中打開Excel文件,并提供了相關(guān)的代碼解釋、數(shù)據(jù)插入、單元格格式設(shè)置和頁面格式設(shè)置的方法2024-12-12

