網(wǎng)站首頁 編程語言 正文
C#調(diào)用python腳本
在平常工程項(xiàng)目開發(fā)過程中常常會涉及到機(jī)器學(xué)習(xí)、深度學(xué)習(xí)算法方面的開發(fā)任務(wù),但是受限于程序設(shè)計(jì)語言本身的應(yīng)用特點(diǎn),該類智能算法的開發(fā)任務(wù)常常使用Python語言開發(fā),所以在工程實(shí)踐過程中常常會遇到多平臺程序部署問題。本文總結(jié)了C#調(diào)用Python程序的各種方法,希望能夠給各位讀者提供一定的參考。
方式一
使用c#,nuget管理包上下載的ironPython安裝包適用于python腳本中不包含第三方模塊的情況
IronPython 是一種在 NET 和 Mono 上實(shí)現(xiàn)的 Python 語言,由 Jim Hugunin(同時(shí)也是 Jython 創(chuàng)造者)所創(chuàng)造。它的誕生是為了將更多的動態(tài)語音移植到NET Framework上。
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);//調(diào)用腳本文件中對應(yīng)的函數(shù)
Console.WriteLine(reStr);
Console.ReadKey();
}
}
}
def main(arr):
try:
arr = set(arr)
arr = sorted(arr)
arr = arr[0:]
return str(arr)
except Exception as err:
return str(err)
方式二
適用于python腳本中包含第三方模塊的情況(與第四種類似)
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])
方式三
使用c++程序調(diào)用python文件,然后將其做成動態(tài)鏈接庫(dll),在c#中調(diào)用此dll文件? ? ?
限制:實(shí)現(xiàn)方式很復(fù)雜,并且受python版本、(python/vs)32/64位影響,而且要求用戶必須安裝python運(yùn)行環(huán)境
方式四
使用安裝好的python環(huán)境,利用c#命令行,調(diào)用.py文件執(zhí)行(推薦使用)
優(yōu)點(diǎn):執(zhí)行速度只比在python本身環(huán)境中慢一點(diǎn),步驟也相對簡單
缺點(diǎn):需要用戶安裝配置python環(huán)境
實(shí)用步驟:
1、下載安裝python,并配置好環(huán)境變量等(本人用的Anaconda,鏈接此處不再提供)
2、編寫python文件(這里為了便于理解,只傳比較簡單的兩個(gè)參數(shù))
#main.py
import numpy as np
import multi
import sys
?
def func(a,b):
? ? result=np.sqrt(multi.multiplication(int(a),int(b)))
? ? return result
?
?
if __name__ == '__main__':
? ? print(func(sys.argv[1],sys.argv[2]))
? ? ? ? 3、在c#中調(diào)用上述主python文件:main.py
? ? ? ? private void Button_Click(object sender, RoutedEventArgs e)
? ? ? ? {
?
? ? ? ? ? ? string[] strArr=new string[2];//參數(shù)列表
? ? ? ? ? ? string sArguments = @"main.py";//這里是python的文件名字
? ? ? ? ? ? strArr[0] = "2";
? ? ? ? ? ? strArr[1] = "3";
? ? ? ? ? ? RunPythonScript(sArguments, "-u", strArr);
? ? ? ? }
? ? ? ? //調(diào)用python核心代碼
? ? ? ? public static void RunPythonScript(string sArgName, string args = "", params string[] teps)
? ? ? ? {
? ? ? ? ? ? Process p = new Process();
? ? ? ? ? ? string path = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + sArgName;// 獲得python文件的絕對路徑(將文件放在c#的debug文件夾中可以這樣操作)
? ? ? ? ? ? path = @"C:\Users\user\Desktop\test\"+sArgName;//(因?yàn)槲覜]放debug下,所以直接寫的絕對路徑,替換掉上面的路徑了)
? ? ? ? ? ? p.StartInfo.FileName = @"D:\Python\envs\python3\python.exe";//沒有配環(huán)境變量的話,可以像我這樣寫python.exe的絕對路徑。如果配了,直接寫"python.exe"即可
? ? ? ? ? ? string sArguments = path;
? ? ? ? ? ? foreach (string sigstr in teps)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? sArguments += " " + sigstr;//傳遞參數(shù)
? ? ? ? ? ? }
?
? ? ? ? ? ? ? ? sArguments += " " + args;
?
? ? ? ? ? ? p.StartInfo.Arguments = sArguments;
?
? ? ? ? ? ? p.StartInfo.UseShellExecute = false;
?
? ? ? ? ? ? p.StartInfo.RedirectStandardOutput = true;
?
? ? ? ? ? ? p.StartInfo.RedirectStandardInput = true;
?
? ? ? ? ? ? p.StartInfo.RedirectStandardError = true;
?
? ? ? ? ? ? p.StartInfo.CreateNoWindow = true;
?
? ? ? ? ? ? p.Start();
? ? ? ? ? ? p.BeginOutputReadLine();
? ? ? ? ? ? p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
? ? ? ? ? ? Console.ReadLine();
? ? ? ? ? ? p.WaitForExit();
? ? ? ? }
? ? ? ? //輸出打印的信息
? ? ? ? static void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
? ? ? ? {
? ? ? ? ? ? if (!string.IsNullOrEmpty(e.Data))
? ? ? ? ? ? {
? ? ? ? ? ? ? ? AppendText(e.Data + Environment.NewLine);
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? public delegate void AppendTextCallback(string text);
? ? ? ? public static void AppendText(string text)
? ? ? ? {
? ? ? ? ? ? Console.WriteLine(text); ? ? //此處在控制臺輸出.py文件print的結(jié)果
?
? ? ? ? }
方式五
c#調(diào)用python可執(zhí)行exe文件,使用命令行進(jìn)行傳參取返回值
優(yōu)點(diǎn):無需安裝python運(yùn)行環(huán)境
缺點(diǎn):
1、可能是因?yàn)橐归_exe中包含的python環(huán)境,執(zhí)行速度相當(dāng)慢,慎用!
2、因?yàn)槭敲钚袀鲄⑿问剑蕚鲄⑿枰孕刑幚怼s:由于命令行傳參形式為:xxx.exe 參數(shù)1 參數(shù)2 參數(shù)3....
使用步驟:
1、使用pyinstaller打包python程序;
2、在c#中調(diào)用此exe文件;?
原文鏈接:https://blog.csdn.net/mago2015/article/details/119450865
相關(guān)推薦
- 2022-12-23 C++中類的構(gòu)造函數(shù)初始值列表解讀_C 語言
- 2022-03-26 C語言goto語句簡單使用詳解_C 語言
- 2022-08-03 python自動化測試用例全對偶組合與全覆蓋組合比較_python
- 2022-07-26 Springboot 解決跨域問題
- 2022-04-11 記錄ElasticSearch在Linux中的常見問題
- 2022-08-03 Python類的基本寫法與注釋風(fēng)格介紹_python
- 2022-05-19 Nginx+Windows搭建域名訪問環(huán)境的操作方法_nginx
- 2022-03-23 詳細(xì)聊聊Redis的過期策略_Redis
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支