C#如何调用python脚本_第1页
C#如何调用python脚本_第2页
C#如何调用python脚本_第3页
C#如何调用python脚本_第4页
C#如何调用python脚本_第5页
已阅读5页,还剩3页未读, 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

第C#如何调用python脚本目录C#调用python脚本方式一方式二方式三方式四方式五

C#调用python脚本

在平常工程项目开发过程中常常会涉及到机器学习、深度学习算法方面的开发任务,但是受限于程序设计语言本身的应用特点,该类智能算法的开发任务常常使用Python语言开发,所以在工程实践过程中常常会遇到多平台程序部署问题。本文总结了C#调用Python程序的各种方法,希望能够给各位读者提供一定的参考。

方式一

使用c#,nuget管理包上下载的ironPython安装包适用于python脚本中不包含第三方模块的情况

IronPython是一种在NET和Mono上实现的Python语言,由JimHugunin(同时也是Jython创造者)所创造。它的诞生是为了将更多的动态语音移植到NETFramework上。

usingIronPython.Hosting;

usingMicrosoft.Scripting.Hosting;

usingSystem;

namespaceCSharpCallPython

classProgram

staticvoidMain(string[]args)

ScriptEnginepyEngine=Python.CreateEngine();//创建Python解释器对象

dynamicpy=pyEngine.ExecuteFile(@"test.py");//读取脚本文件

int[]array=newint[9]{9,3,5,7,2,1,3,6,8};

stringreStr=py.main(array);//调用脚本文件中对应的函数

Console.WriteLine(reStr);

Console.ReadKey();

}

defmain(arr):

try:

arr=set(arr)

arr=sorted(arr)

arr=arr[0:]

returnstr(arr)

exceptExceptionaserr:

returnstr(err)

方式二

适用于python脚本中包含第三方模块的情况(与第四种类似)

usingSystem;

usingSystem.Collections;

usingSystem.Diagnostics;

namespaceTest

classProgram

staticvoidMain(string[]args)

Processp=newProcess();

stringpath="reset_ipc.py";//待处理python文件的路径,本例中放在debug文件夹下

stringsArguments=path;

ArrayListarrayList=newArrayList();

arrayList.Add("com4");

arrayList.Add(57600);

arrayList.Add("password");

foreach(varparaminarrayList)//添加参数

sArguments+=""+sigstr;

p.StartInfo.FileName=@"D:\Python2\python.exe";//python2.7的安装路径

p.StartInfo.Arguments=sArguments;//python命令的参数

p.StartInfo.UseShellExecute=false;

p.StartInfo.RedirectStandardOutput=true;

p.StartInfo.RedirectStandardInput=true;

p.StartInfo.RedirectStandardError=true;

p.StartInfo.CreateNoWindow=true;

p.Start();//启动进程

Console.WriteLine("执行完毕!");

Console.ReadKey();

}

Python代码

#-*-coding:UTF-8-*-

importserial

importtime

defresetIPC(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-9xxx\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)

exceptException:

flag=False

finally:

ser.close()

returnflag

resetIPC(sys.argv[1],sys.argv[2],sys.argv[3])

方式三

使用c++程序调用python文件,然后将其做成动态链接库(dll),在c#中调用此dll文件

限制:实现方式很复杂,并且受python版本、(python/vs)32/64位影响,而且要求用户必须安装python运行环境

方式四

使用安装好的python环境,利用c#命令行,调用.py文件执行(推荐使用)

优点:执行速度只比在python本身环境中慢一点,步骤也相对简单

缺点:需要用户安装配置python环境

实用步骤:

1、下载安装python,并配置好环境变量等(本人用的Anaconda,链接此处不再提供)

2、编写python文件(这里为了便于理解,只传比较简单的两个参数)

#main.py

importnumpyasnp

importmulti

importsys

deffunc(a,b):

result=np.sqrt(multi.multiplication(int(a),int(b)))

returnresult

if__name__=='__main__':

print(func(sys.argv[1],sys.argv[2]))

3、在c#中调用上述主python文件:main.py

privatevoidButton_Click(objectsender,RoutedEventArgse)

{

string[]strArr=newstring[2];//参数列表

stringsArguments=@"main.py";//这里是python的文件名字

strArr[0]="2";

strArr[1]="3";

RunPythonScript(sArguments,"-u",strArr);

}

//调用python核心代码

publicstaticvoidRunPythonScript(stringsArgName,stringargs="",paramsstring[]teps)

{

Processp=newProcess();

stringpath=System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase+sArgName;//获得python文件的绝对路径(将文件放在c#的debug文件夹中可以这样操作)

path=@"C:\Users\user\Desktop\test\"+sArgName;//(因为我没放debug下,所以直接写的绝对路径,替换掉上面的路径了)

p.StartInfo.FileName=@"D:\Python\envs\python3\python.exe";//没有配环境变量的话,可以像我这样写python.exe的绝对路径。如果配了,直接写"python.exe"即可

stringsArguments=path;

foreach(stringsigstrinteps)

{

sArguments+=""+sigstr;//传递参数

}

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+=newDataReceivedEventHandler(p_OutputDataReceived);

Console.ReadLine();

p.WaitForExit();

}

//输出打印的信息

staticvoidp_OutputDataReceived(objectsender,DataReceivedEventArgse)

{

if(!string.IsNullOrEmpty(e.Data))

{

AppendText(e.Data+Environment.NewLine);

}

}

publicdelegatevoidAppendTextCallback(stringtext);

publicstaticvoidAppendText(stringtext)

{

Console.WriteLine(text);

//此处在控制台输出.py文件print的结果

}

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论