当前位置: 移动技术网 > IT编程>开发语言>c# > C#调用python脚本的方法步骤(2种)

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

2020年03月09日  | 移动技术网IT编程  | 我要评论

因项目需要,需要使用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 serial
import time

def 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 flag

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

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

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网