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

方式一:适用于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脚本时,需要在Python安装目录且包含第三方模块文件夹;打包时可以拷贝该文件到程序运行目录,直接打包进去

 

  • 0
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值