C#調用Python代碼


C#中,如果碰到需要調用Python代碼時,一種方法是使用IronPython,不過這種方法太繁瑣太累,特別是碰到Python代碼中帶有大量的第三方包,就會一直報錯,提示缺少相應模塊,這種方法太low,只支持Python2代碼,果斷摒棄。推薦另一種方法是用pyinstaller打包Python程序,會自動將程序中引用的第三方包也打包進去,Python3.X隨便用,很方便。pyinstaller怎么安裝就不用說了,下面介紹下pyinstaller打包的過程和c#調用的過程。

1、現在,在你的電腦桌面有一個Python文件(名字為secondcompare.py)需要打包,里面的代碼如下:

import difflib
import pandas as pd
import sys

def compare(fundname, securityname):
    ratio = difflib.SequenceMatcher(None, fundname, securityname).ratio()
    return ratio

def second(fundname,securityname_string):
    securityname_list = []
    if '\n' in securityname_string:
        fund = securityname_string.split('\n')
        for line in fund:
            if len(line) > 0:
                line = line.strip()
                line = line.rstrip('\r')
                securityname_list.append(line)
    else:
        securityname_list.append(securityname_string)
    ratio_list = [(fundname, securityname, compare(fundname, securityname)) for securityname in securityname_list]
    pd_result = pd.DataFrame(ratio_list, columns=['FundName', 'SecurityName', 'Ratio']).sort_values(by='Ratio', ascending=False)
    return pd_result.head(1).values.tolist()[0][1]
    
if __name__=='__main__':
    # fundname="Ivy VIP High Income II"
    # securityname_string='''Janus Henderson VIT Overseas Portfolio: Service Shares\n
    # Janus Henderson VIT Forty Portfolio: Service Shares\n
    # Fidelity Variable Insurance Products Fund - VIP High Income Portfolio: Service Class
    # '''
    fundname=sys.argv[1]
    securityname_string=sys.argv[2]
    a=second(fundname,securityname_string)
    print(a)
View Code

2、打開cmd命令窗口,先執行cd C:\Users\jlin10\Desktop進入到桌面路徑(用戶名自己改),然后執行pyinstaller -F -i icon.ico secondcompare.py,pyinstaller的各個參數設置可以參考https://blog.csdn.net/weixin_39000819/article/details/80942423。然后cmd就開始跑,到最后提示打包成功,結果在桌面生成了一個與Python文件同名的spec文件和三個文件夾__pycache__、build、dist,打包好的exe程序就放在dist文件夾里。

 

 

 

 

 

 

3、接下來在C#中調用這個secondcompare.exe,把第2步生成的四個東西剪切到C#的debug文件夾里,引用using System.Diagnostics;,輸入以下代碼:

string temppath = System.AppDomain.CurrentDomain.BaseDirectory.ToString();
Process p = new Process();
p.StartInfo.FileName = temppath + "\\dist\\secondcompare.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.CreateNoWindow = true;
string arg1="Ivy VIP High Income II";
string arg2="Janus Henderson VIT Overseas Portfolio: Service Shares\nJanus Henderson VIT Forty Portfolio: Service Shares\nFidelity Variable Insurance Products Fund - VIP High Income Portfolio: Service Class";
p.StartInfo.Arguments ="\"" + arg1 + "\"" + " " + "\"" + arg2+ "\"";
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
p.Close();
MessageBox.Show(output);

其中,參數間是用空格分隔的,這里兩個參數都帶有空格,不能直接相連,要先用"\""括起來,中間再用空格相連。

最后,附上Python代碼文件和用到的圖標

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM