C#调用python脚本,,只尝试了两种调用方式
C#调用python脚本,,只尝试了两种调用方式
只尝试了两种调用方式,第一种只适用于python脚本中不包含第三方模块的情况,第二种针对的是python脚本中包含第三方模块的情况。不管哪种方式,首先都需要安装IronPython。可以在官网下载安装包自行安装后添加引用即可。
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)
注意
Q:找不到py文件
A:检查最后执行文件路径,可能需要将文件属性中“复制到输出目录”设置为“始终复制”
Q:py文件方法执行异常
A:检查py文件可否单独执行,如果可以执行,检查执行环境是否为3.x,可能需要py代码降级;如果不可执行,检查是否引用第三方包,第三方是否非全局安装
Tip:目前 IronPython 支持Python模拟运行环境为2.x
结果
方式二:适用于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()方式,调试有各种问题,最终放弃了,没有研究。
git地址
C#调用python脚本
相关内容
- python面试不得不知道的点——GIL,,# 百度搜索:pyt
- 14、python异常处理及断言,,前言:本文主要介绍p
- python总结,,map()函数map
- Linux Shell curl 和 wget 使用代理IP,,
- selenium 常见操作,上传操作,,上传操作有两种情况:
- python列表生成式应用案例,,什么是列表生成式?列
- python中的map()函数,,python中的ma
- tmp 20191101-----windows vim python开发环境配置,,安装下载
- 不同 Python 数据类型的搜寻,,不同 Python
- python 小故事1,python小故事,def test(a
评论关闭