Csharp/C#教程:C#调用python脚本的方法步骤(2种)分享

因项目需要,需要使用C#控制台程序执行python脚本,查询各种资料后可以成功调用了,记录一下,以备后面遗忘。

只尝试了两种调用方式,第一种只适用于python脚本中不包含第三方模块的情况,第二种针对的是python脚本中包含第三方模块的情况。不管哪种方式,首先都需要安装IronPython。我是通过vs2017的工具->NuGet包管理器->管理解决方案的NuGet包,搜索IronPython包安装,也可以在官网下载安装包自行安装后添加引用即可。

方式一:适用于python脚本中不包含第三方模块的情况

C#代码 

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(); } } }

python脚本

defmain(arr): try: arr=set(arr) arr=sorted(arr) arr=arr[0:] returnstr(arr) exceptExceptionaserr: returnstr(err)

结果

C#调用python脚本的方法步骤(2种)

方式二:适用于python脚本中包含第三方模块的情况

C#代码

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:Python2python.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("rootn".encode("utf-8")) time.sleep(1) passwordStr="%sn"%password ser.write(passwordStr.encode("utf-8")) time.sleep(1) ser.write("killall-9xxxn".encode("utf-8")) time.sleep(1) ser.write("rm/etc/xxx/xxx_user.*n".encode("utf-8")) time.sleep(1) ser.write("rebootn".encode("utf-8")) time.sleep(1) exceptException: flag=False finally: ser.close() returnflag resetIPC(sys.argv[1],sys.argv[2],sys.argv[3])

上面的python脚本实现的是重启IPC设备,测试功能成功。

调用包含第三方模块的python脚本时,尝试过使用path.append()方式,调试有各种问题,最终放弃了,没有研究。

您可能感兴趣的文章:在VS2017中用C#调用python脚本的实现详解Python调用C#dll库最简方法Python调用C#Comdll组件实战教程C#调用Python模块的方法C#调用python文件执行C#调用Python脚本的简单示例

标签: python 脚本 方法 调用 python脚本 用python

c#使用linq把多列的List转化为只有指定列的List

Unity3D实现射线使物体移动

上述就是C#学习教程:C#调用python脚本的方法步骤(2种)分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/904040.html

(0)
上一篇 2021年10月21日
下一篇 2021年10月21日

精彩推荐