温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C#调用python脚本的方法步骤是怎样的

发布时间:2021-10-28 18:03:01 来源:亿速云 阅读:277 作者:柒染 栏目:编程语言

这期内容当中小编将会给大家带来有关C#调用python脚本的方法步骤是怎样的,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

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

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

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

C#代码 

using IronPython.Hosting;using Microsoft.Scripting.Hosting;using System;namespace CSharpCallPython{  class Program  {    static void Main(string[] args)    {      ScriptEngine pyEngine = Python.CreateEngine();//创建Python解释器对象      dynamic py = pyEngine.ExecuteFile(@"test.py");//读取脚本文件      int[] array = new int[9] { 9, 3, 5, 7, 2, 1, 3, 6, 8 };      string reStr = py.main(array);//调用脚本文件中对应的函数      Console.WriteLine(reStr);      Console.ReadKey();    }  }}

python脚本

def main(arr):  try:    arr = set(arr)    arr = sorted(arr)    arr = arr[0:]    return str(arr)  except Exception as err:    return str(err)

结果

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

C#代码

using System;using System.Collections;using System.Diagnostics;namespace Test{  class Program  {    static void Main(string[] args)    {      Process p = new Process();      string path = "reset_ipc.py";//待处理python文件的路径,本例中放在debug文件夹下      string sArguments = path;      ArrayList arrayList = new ArrayList();      arrayList.Add("com4");      arrayList.Add(57600);      arrayList.Add("password");      foreach (var param in arrayList)//添加参数      {        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 -*-import serialimport timedef resetIPC(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 -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("reboot\n".encode("utf-8"))    time.sleep(1)  except Exception:    flag=False  finally:    ser.close()  return flagresetIPC(sys.argv[1], sys.argv[2], sys.argv[3])

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

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

上述就是小编为大家分享的C#调用python脚本的方法步骤是怎样的了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI