詳解c#與python的交互方式
前言:
在平時工作中,需求有多種實現(xiàn)方式;根據(jù)不同的需求可以采用不同的編程語言來實現(xiàn)。發(fā)揮各種語言的強項
如:Python的強項是:數(shù)據(jù)分析、人工智能等
.NET 開發(fā)桌面程序界面比Python更簡單、方便、美觀
那么就存在各種語言間交互,本篇主要介紹幾種C# 與 Python的交互方式。
一、IronPython
1、IronPython是什么?
IronPython是Python編程語言的開源實現(xiàn),該語言與.NET Framework緊密集成。IronPython可以使用.NET Framework和Python庫,而其他.NET語言也可以輕松使用Python代碼。
2、IrconPython如何使用
a) 添加包引用:
Install-Package IronPython -Version 2.7.11
b) 執(zhí)行簡單python腳本:
//創(chuàng)建執(zhí)行引擎
ScriptEngine engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();
string script = "'Hello %d' %number";
//設(shè)置參數(shù)列表
scope.SetVariable("number", 123);
ScriptSource sourceCode = engine.CreateScriptSourceFromString(script);
var result = sourceCode.Execute<object>(scope);
c) 執(zhí)行python文件方法:
添加如下簡單Python文件:demo.py
#文件目錄 demo.py
import time
def welcome(name):
return "hello " + name
def Add(a, b):
return a + b
def showMsg(name,birthday):
return "姓名:" + name + ",生日:" + birthday
執(zhí)行方法:
string path = @"demo.py"; ScriptRuntime pyRuntime = Python.CreateRuntime(); //創(chuàng)建一下運行環(huán)境 dynamic obj = pyRuntime.UseFile(path); //調(diào)用python中Add函數(shù) object sum = obj.Add(1, 54);
d) 執(zhí)行python文件方法(依賴三方庫):
from scipy import linalg
import numpy as np
import json
def calcnum(jsonInput):
A = np.array([[1, 1, 7], [2, 3, 5], [4, 2, 6]]) # A代表系數(shù)矩陣
b = np.array([2, 3, 4]) # b代表常數(shù)列
x = linalg.solve(A, b)
# json字符串轉(zhuǎn)對象
info = json.loads(jsonInput)
print(info['a'])
# 對象轉(zhuǎn)json字符串
output = json.dumps(info)
print(output)
print(x)
執(zhí)行結(jié)果:

IronPython雖然能夠交互Python,但支持的庫不多,當py文件依賴三方庫,則會調(diào)用失?。磺襂ronPython對Python3尚未完全支持,下面就開始在C#在Python有第三方庫的情況下交互Python。
二、Python打包exe調(diào)用
把Python打包成exe,C#再通過cmd進行交互。就可以解決第三方庫的問題;
修改Python文件(calc.py):依賴了scipy庫
from scipy import linalg
import numpy as np
import json
def calcnum(jsonInput):
A = np.array([[1, 1, 7], [2, 3, 5], [4, 2, 6]]) # A代表系數(shù)矩陣
b = np.array([2, 3, 4]) # b代表常數(shù)列
x = linalg.solve(A, b)
# json字符串轉(zhuǎn)對象
info = json.loads(jsonInput)
print(info['a'])
# 對象轉(zhuǎn)json字符串
output = json.dumps(info)
print(output)
print(x)
if __name__ == '__main__':
inputString = sys.argv[1]
calcnum(inputString)
Pyinstaller:
PyInstaller 是一個程序,將(包)Python 程序打包到獨立的可執(zhí)行文件中,在 Windows、Linux、Mac OS X、FreeBSD、Solaris 和 AIX 下。與類似工具不同,它的主要優(yōu)點是 PyInstaller 可以與 Python 2.7 和 3.3_3.5 配合使用,它通過透明壓縮構(gòu)建更小的可執(zhí)行文件,它是完全多平臺的,并使用操作系統(tǒng)支持來加載動態(tài)庫,從而確保完整兼容性。
PyInstaller 的主要目標是與開箱即用的第三方軟件包兼容。這意味著,使用 PyInstaller 時,所有使外部包正常工作所需的技巧都已集成到 PyInstaller 本身中,因此無需用戶干預(yù)。您永遠不需要在 wiki 中查找技巧,并將自定義修改應(yīng)用于文件或設(shè)置腳本。例如,像PyQt、Django或matplotlib這樣的庫完全支持,而無需手動處理插件或外部數(shù)據(jù)文件。
安裝:
在Cmd命令行中運行:需提前安裝pip(python3.4以后默認包含)
pip install pyinstaller
打包:
//命令格式 pyinstaller 選項 Python 源文件
選項參數(shù)支持以下內(nèi)容:
| 參數(shù) | 描述 |
|---|---|
| -H, -help | 查看幫助文檔 |
| -F,-onefile | 產(chǎn)生單個的可執(zhí)行文件 |
| -D,--onedir | 產(chǎn)生一個目錄(包含多個文件)作為可執(zhí)行程序 |
| -a,--ascii | 不包含 Unicode 字符集支持 |
| -d,--debug | 產(chǎn)生 debug 版本的可執(zhí)行文件 |
| -w,--windowed,--noconsolc | 指定程序運行時不顯示命令行窗口(僅對 Windows 有效) |
| -c,--nowindowed,--console | 指定使用命令行窗口運行程序(僅對 Windows 有效) |
| -o DIR,--out=DIR | 指定 spec 文件的生成目錄。如果沒有指定,則默認使用當前目錄來生成 spec 文件 |
| -p DIR,--path=DIR | 設(shè)置 Python 導入模塊的路徑(和設(shè)置 PYTHONPATH 環(huán)境變量的作用相似)。也可使用路徑分隔符(Windows 使用分號,Linux 使用冒號)來分隔多個路徑 |
| -n NAME,--name=NAME | 指定項目(產(chǎn)生的 spec)名字。如果省略該選項,那么第一個腳本的主文件名將作為 spec 的名字 |
最后在命令行中執(zhí)行命令:
pyinstaller -F calc.py
打包完成后,生成calc.exe文件:

調(diào)用:
private string Calc(string inputString)
{
// 調(diào)用python腳本
Process p = new Process();
p.StartInfo.FileName = "calc.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.CreateNoWindow = true;
// 注意,這前面得有一個空格,不然就連在一起了
p.StartInfo.Arguments = " " + inputString;
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
p.Close(); return output;
}
到此該方法已能成功調(diào)用Python結(jié)果
三、Python提供WebApi接口(推薦)
使用Python中flask庫實現(xiàn)一個簡單的webapi服務(wù):
from flask import Flask, request
import Math
app = Flask(__name__)
@app.route("/")
def welcome():
return "Hello World!"
@app.route("/calc")
def calc():
strinput = request.args.get("jsonInput")
return Math.calcnum(strinput)
if __name__ == "__main__":
app.run()
最后在C#中調(diào)用webapi:得到python結(jié)果

總結(jié):
通過以上內(nèi)容知道各種語言平臺想交互,雖然有多種方式實現(xiàn);但是最為推薦還是提供Webapi接口方式。
以上就是詳解c#與python的交互方式的詳細內(nèi)容,更多關(guān)于c#與python的交互的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
使用VS2010 C#開發(fā)ActiveX控件(下),完整代碼打包下載
我們介紹了開發(fā)、打包、發(fā)布、使用ActiveX控件的全過程。在演示程序中,我們沒有調(diào)用串口通信和讀卡器Dll程序,由于我們讀卡器的原始Dll是使用其它語言進行開發(fā)的,對C#來說,是非托管代碼,因此我們還需要在代碼級別進行非托管代碼的安全性設(shè)置2011-05-05
C#實現(xiàn)winform中RichTextBox在指定光標位置插入圖片的方法
這篇文章主要介紹了C#實現(xiàn)winform中RichTextBox在指定光標位置插入圖片的方法,涉及RichTextBox控件及剪切板的相關(guān)操作技巧,非常簡單實用,需要的朋友可以參考下2016-06-06
C#獲取鼠標在listview右鍵點擊單元格的內(nèi)容方法
下面小編就為大家?guī)硪黄狢#獲取鼠標在listview右鍵點擊單元格的內(nèi)容方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-01-01
C#聯(lián)合VisionPro實現(xiàn)TCP/IP通信詳解
TCP/IP(傳輸控制協(xié)議/互聯(lián)網(wǎng)協(xié)議)是一組用于在網(wǎng)絡(luò)上進行通信的通信協(xié)議,本文主要為大家詳細介紹了C#如何聯(lián)合VisionPro實現(xiàn)TCP/IP通信,希望對大家有所幫助2024-02-02
深入Resource實現(xiàn)多語言支持的應(yīng)用詳解
本篇文章是對Resource實現(xiàn)多語言支持的應(yīng)用進行了詳細的分析介紹,需要的朋友參考下2013-05-05

