只嘗試了兩種調用方式,第一種只適用於python腳本中不包含第三方模塊的情況,第二種針對的是python腳本中包含第三方模塊的情況。不管哪種方式,首先都需要安裝IronPython。可以在官網下載安裝包自行安裝后添加引用即可。
C#代碼
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using System;
namespace CSharpCallPython
{
class Program
{
static void Main(string[] args)
{
ScriptEngine pyEngine = Python.CreateEngine();//創建Python解釋器對象
dynamic py = pyEngine.ExecuteFile(@"test.py");//讀取腳本文件
int[] array = new int[9] { 9, 3, 5, 7, 2, 1, 3, 6, 8 };
string reStr = py.main(array);//調用腳本文件中對應的函數
Console.WriteLine(reStr);
Console.ReadKey();
}
}
}
python代碼
def main(arr):
try:
arr = set(arr)
arr = sorted(arr)
arr = arr[0:]
return str(arr)
except Exception as err:
return str(err)
注意
Q:找不到py文件
A:檢查最后執行文件路徑,可能需要將文件屬性中“復制到輸出目錄”設置為“始終復制”
Q:py文件方法執行異常
A:檢查py文件可否單獨執行,如果可以執行,檢查執行環境是否為3.x,可能需要py代碼降級;如果不可執行,檢查是否引用第三方包,第三方是否非全局安裝
Tip:目前 IronPython 支持Python模擬運行環境為2.x
結果
方式二:適用於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)//添加參數
{
sArguments += " " + sigstr;
}
p.StartInfo.FileName = @"D:\Python2\python.exe"; //python2.7的安裝路徑
p.StartInfo.Arguments = sArguments;//python命令的參數
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();//啟動進程
Console.WriteLine("執行完畢!");
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腳本實現的是重啟IPC設備,測試功能成功。
調用包含第三方模塊的python腳本時,嘗試過使用path.append()方式,調試有各種問題,最終放棄了,沒有研究。