介绍
小编给大家分享一下c#如何调用python脚本,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获、下面让我们一起去了解一下吧!
只尝试了两种调用方式,第一种只适用于python脚本中不包含第三方模块的情况,第二种针对的是python脚本中包含第三方模块的情况。不管哪种方式,首先都需要安装IronPython。我是通过vs2017的工具→NuGet包管理器→管理解决方案的NuGet包,搜索IronPython包安装,也可以在官网下载安装包自行安装后添加引用即可。
<强>方式一:适用于python脚本中不包含第三方模块的情况强>
c#代码
using IronPython.Hosting; using Microsoft.Scripting.Hosting; using 系统; namespace CSharpCallPython { class 才能;程序 {才能 ,,,static void Main (string [], args) ,,,{ ,,,,,ScriptEngine pyEngine =, Python.CreateEngine();//创建Python解释器对象 ,,,,,dynamic py =, pyEngine.ExecuteFile (@" test.py");//读取脚本文件 ,,,,,int [], array =, new int [9], {,, 3, 5, 7,, 2,, 1,, 3,, 6, 8,}; ,,,,,string reStr =, py.main(数组);//调用脚本文件中对应的函数 ,,,,,Console.WriteLine (reStr); ,,,,,Console.ReadKey (); ,,,} ,,} }
python脚本
def 主要(arr): 尝试才能: ,,,arr =,集(arr) ,,,arr =,排序(arr) ,,,arr =, arr (0:) ,,,return str (arr) except 才能;Exception  as 错: ,,,return str (err)
结果
<强>方式二:适用于python脚本中包含第三方模块的情况强>
c#代码
using 系统; using System.Collections; using System.Diagnostics; namespace 测试 { class 才能;程序 {才能 ,,,static void Main (string [], args) ,,,{ ,,,,,Process p =, new 过程(); ,,,,,string path =,“reset_ipc.py"//待处理python文件的路径,本例中放在调试文件夹下 ,,,,,string sArguments =,路径; ,,,,,ArrayList ArrayList =, new ArrayList (); ,,,,,arrayList.Add (“com4"); ,,,,,arrayList.Add (57600); ,,,,,arrayList.Add (“password"); ,,,,,foreach (var param  arrayList拷贝)//添加参数 ,,,,,{ ,,,,,,,sArguments +=,,,,, +, sigstr; ,,,,,} ,,,,,p.StartInfo.FileName =, @" D: \ Python2 \ python.exe",,//python2.7的安装路径 ,,,,,p.StartInfo.Arguments =, sArguments;//python命令的参数 ,,,,,p.StartInfo.UseShellExecute =,假; ,,,,,p.StartInfo.RedirectStandardOutput =,真的; ,,,,,p.StartInfo.RedirectStandardInput =,真的; ,,,,,p.StartInfo.RedirectStandardError =,真的; ,,,,,p.StartInfo.CreateNoWindow =,真的; ,,,,,p.Start();//启动进程 ,,,,,Console.WriteLine(“执行完毕!“); ,,,,,Console.ReadKey (); ,,,} ,,} }
python脚本
#, - *安康;编码:UTF-8 - * - import 串行 import 时间 def resetIPC (com,波特率,,密码,超时=0.5): ser才能=serial.Serial (com,波特率,,超时=超时) ,国旗=True 尝试才能: ,,,ser.close () ,,,ser.open () ,,,ser.write (“\ n" .encode (“utf-8")) ,,,time . sleep (1) ,,,ser.write(“根\ n" .encode (“utf-8")) ,,,time . sleep (1) ,,,passwordStr=? s \ n" %,密码 ,,,ser.write (passwordStr.encode (“utf-8")) ,,,time . sleep (1) ,,,ser.write (“killall  9, xxx \ n" .encode (“utf-8")) ,,,time . sleep (1) ,,,ser.write (“rm /etc/xxx/xxx_user。* \ n" .encode (“utf-8")) ,,,time . sleep (1) ,,,ser.write(“重启\ n" .encode (“utf-8")) ,,,time . sleep (1) null null null null null null nullc#如何调用python脚本