C#調用python腳本的方法步驟(2種)
因項目需要,需要使用C#控制臺程序執(zhí)行python腳本,查詢各種資料后可以成功調用了,記錄一下,以備后面遺忘。
只嘗試了兩種調用方式,第一種只適用于python腳本中不包含第三方模塊的情況,第二種針對的是python腳本中包含第三方模塊的情況。不管哪種方式,首先都需要安裝IronPython。我是通過vs2017的工具->NuGet包管理器->管理解決方案的NuGet包,搜索IronPython包安裝,也可以在官網(wǎng)下載安裝包自行安裝后添加引用即可。
方式一:適用于python腳本中不包含第三方模塊的情況
C#代碼
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using System;
namespace CSharpCallPython
{
class Program
{
static void Main(string[] args)
{
ScriptEngine pyEngine = Python.CreateEngine();//創(chuàng)建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);//調用腳本文件中對應的函數(shù)
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)
結果

方式二:適用于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();//啟動進程
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設備,測試功能成功。
調用包含第三方模塊的python腳本時,嘗試過使用path.append()方式,調試有各種問題,最終放棄了,沒有研究。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
C# Winform中實現(xiàn)主窗口打開登錄窗口關閉的方法
這篇文章主要介紹了C# Winform中實現(xiàn)主窗口打開登錄窗口關閉的方法,這在需要用戶名密碼的軟件項目中是必用的一個技巧,要的朋友可以參考下2014-08-08
CPF?使用C#的Native?AOT?發(fā)布程序的詳細過程
這篇文章主要介紹了CPF?使用C#的Native?AOT?發(fā)布程序,本文給大家介紹的非常詳細,對大家的學習或工作具體一定的參考借鑒價值,需要的朋友可以參考下2022-03-03
c#打印預覽控件中實現(xiàn)用鼠標移動頁面功能代碼分享
項目中需要實現(xiàn)以下功能:打印預覽控件中,可以用鼠標拖動頁面,以查看超出顯示范圍之外的部分內容,下面就是實現(xiàn)代碼2013-12-12

