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

作者:Zoe_yan 时间:2021-11-12 02:44:09 

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

结果

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

方式二:适用于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()方式,调试有各种问题,最终放弃了,没有研究。

来源:https://www.cnblogs.com/zoe-yan/p/10374757.html

标签:C#,调用,python
0
投稿

猜你喜欢

  • 通过python爬虫赚钱的方法

    2023-04-27 11:48:17
  • 收集的ORACLE函数大全

    2010-07-16 12:58:00
  • PHP信号处理机制的操作代码讲解

    2023-07-14 09:26:49
  • django 解决manage.py migrate无效的问题

    2021-08-18 02:28:51
  • 从 msxml6.dll 中获取 DOMDocument 对象的方法与属性

    2009-02-22 18:46:00
  • PHP未登录自动跳转到登录页面

    2023-11-15 07:39:11
  • 基于Python计算圆周率pi代码实例

    2021-03-06 05:13:17
  • ASP + Serv-u 实现FTP的代码

    2009-02-02 09:52:00
  • css样式表滤镜全接触

    2007-10-26 12:48:00
  • Python中re模块:匹配开头/结尾(^/$)

    2021-08-31 02:29:13
  • 详解Python IO编程

    2021-06-26 08:40:48
  • 详解uniapp页面跳转URL传参大坑

    2023-09-15 09:52:43
  • IE下中英文字体不能对齐原因及解决

    2008-08-11 12:47:00
  • JavaScript 组件之旅(一):分析和设计

    2009-09-21 10:52:00
  • 简单理解Python中的装饰器

    2021-06-18 01:44:21
  • Python笔试面试题小结

    2022-07-17 12:51:23
  • ASP 3.0中的新特性

    2008-02-27 13:28:00
  • asp 静态页面的另一种思路

    2011-04-08 10:32:00
  • SQL语句练习实例之四 找出促销活动中销售额最高的职员

    2011-11-03 16:47:03
  • python 绘制斜率图进行对比分析

    2022-03-18 15:31:38
  • asp之家 网络编程 m.aspxhome.com