两种方法:
一 、直接调用.py文件执行
1.编写hello.py文件(不含第三方库),放在C#项目中的Debug文件目录下3.
def show(str):
print(str)
2.在C#中使用NuGet安装Ironpython 库
3.调用代码
// 直接调用 .py文件
ScriptRuntime pyRunTime = Python.CreateRuntime();
dynamic obj = pyRunTime.UseFile("hello.py");
string out = obj.show("name");
二 、调用Python打包的.exe文件
1.编写hello.py文件
# -*- coding:utf-8 -*-
import urllib.request
import re
import sys
def climb(a,b):
url="http://www.dxjava.cn/qrcode.html" #爬的地址
page=urllib.request.urlopen(url).read() #获取到该地址的所有内容
page=page.decode('gbk') #转码
#正则表达式
zz = r'<h1>(.*?)<\/h1>'
#匹配所有符合规则的内容存到html集合里面
html=re.findall(zz,page,re.S) #re.S表示.可以代表\n
return html
if __name__ == '__main__':
climb(sys.argv[1],sys.argv[2])
2.cmd进入黑窗口安装 Python打包工具
pip install pyinstaller
3.安装完成呢个后,cd 进入hello.py所在目录进行打包
pyinstaller -F hello.py
4.C#调用程序
// 调用.exe文件
string pyexePath = System.Environment.CurrentDirectory + @"\hello.exe";
//此c#项目的debug文件夹路径
//string pyexePath = @"C:\Users\Administrator\PycharmProjects\Search\dist\hello.exe";
//python文件所在路径,一般不使用绝对路径,此处仅作为例子,建议转移到debug文件夹下
Process p = new Process();
p.StartInfo.FileName = pyexePath;//需要执行的文件路径
p.StartInfo.UseShellExecute = false; //必需
p.StartInfo.RedirectStandardOutput = true;//输出参数设定
p.StartInfo.RedirectStandardInput = true;//传入参数设定
p.StartInfo.CreateNoWindow = true;
p.StartInfo.Arguments = "2 3";//参数以空格分隔,如果某个参数为空,可以传入””
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();//关键,等待外部程序退出后才能往下执行}
p.Close();