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 '
' in securityname_string:
        fund = securityname_string.split('
')
        for line in fund:
            if len(line) > 0:
                line = line.strip()
                line = line.rstrip('
')
                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

    # Janus Henderson VIT Forty Portfolio: Service Shares

    # 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:Usersjlin10Desktop进入到桌面路径(用户名自己改),然后执行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
Janus Henderson VIT Forty Portfolio: Service Shares
Fidelity 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代码文件和用到的图标

原文地址:https://www.cnblogs.com/JTCLASSROOM/p/10951084.html