这篇文章介绍了C#使用IronPython库调用Python脚本的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
IronPython是一种在 .NET及 Mono上的 Python实现,由微软的 Jim Hugunin所发起,是一个开源的项目,基于微软的 DLR引擎。
IronPython的主页: IronPython.net /
github站点:
IronLanguages/ironpython3: Implementation of Python 3.x for .NET Framework that is built on top of the Dynamic Language Runtime. (github.com)
IronLanguages/ironpython2: Implementation of the Python programming language for .NET Framework; built on top of the Dynamic Language Runtime (DLR). (github.com)
方式一:适用于python脚本中不包含第三方模块的情况
1、执行语句
借由IronPython,就可以利用.NET执行存储在Python脚本中的代码段。下面通过简单的示例说明如何应用C#调用Python脚本。
1、在VS中新建窗体项目:IronPythonDemo
2、VS的菜单中打开“Nuget程序包管理器”
3、搜索IronPython程序包并安装
安装后自动引用如下的DLL
4、在exe程序所在文件夹下创建Python脚本。Python示例脚本实现求两个数的四则运算:
num1=arg1
num2=arg2
op=arg3
if op==1:
result=num1+num2
elif op==2:
result=num1-num2
elif op==3:
result=num1*num2
else:
result=num1*1.0/num2
设置IronPythonDemo.py文件属性为“复制到输出目录”
5、修改工程的配置文件App.config如下:
其中microsoft.scripting节点中设置了IronPython语言引擎的几个属性。
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="microsoft.scripting" type="Microsoft.Scripting.Hosting.Configuration.Section, Microsoft.Scripting"/>
</configSections>
<microsoft.scripting>
<languages>
<language names="IronPython;Python;py" extensions=".py" displayName="Python" type="IronPython.Runtime.PythonContext, IronPython"/>
</languages>
</microsoft.scripting>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
6、 绘制窗体如下:
7、编写计算的函数:
ScriptRuntime scriptRuntime = ScriptRuntime.CreateFromConfiguration();
ScriptEngine pyEngine = scriptRuntime.GetEngine("python");
ScriptSource source = pyEngine.CreateScriptSourceFromFile("IronPythonDemo.py");//设置脚本文件
ScriptScope scope = pyEngine.CreateScope();
try
{
//设置参数
scope.SetVariable("arg1", Convert.ToInt32(txtNum1.Text));
scope.SetVariable("arg2", Convert.ToInt32(txtNum2.Text));
scope.SetVariable("arg3", operation.SelectedIndex + 1);
}
catch (Exception)
{
MessageBox.Show("输入有误。");
}
source.Execute(scope);
labelResult.Text = scope.GetVariable("result").ToString();
}
8、编译运行可得计算结果(此处未做输入的检查)
2、执行函数
IronPythonDemo2.py
def main(arr):
try:
arr = set(arr)
arr = sorted(arr)
arr = arr[0:]
return str(arr)
except Exception as err:
return str(err)
c#代码
ScriptEngine pyEngine = IronPython.Hosting.Python.CreateEngine();//创建Python解释器对象
dynamic py = pyEngine.ExecuteFile(@"IronPythonDemo2.py");//读取脚本文件
int[] array = new int[9] { 9, 3, 5, 7, 2, 1, 3, 6, 8 };
string reStr = py.main(array);//调用脚本文件中对应的函数
MessageBox.Show(reStr);
//或者
ScriptRuntime pyRuntime = IronPython.Hosting.Python.CreateRuntime(); //创建一下运行环境
dynamic obj = pyRuntime.UseFile("IronPythonDemo2.py"); //调用一个Python文件
int[] array = new int[9] { 9, 3, 5, 7, 2, 1, 3, 6, 8 };
string reStr = obj.main(array);//调用脚本文件中对应的函数
MessageBox.Show(reStr);
方式二:适用于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()方式,调试有各种问题,最终放弃了,没有研究。
到此这篇关于C#使用IronPython库调用Python脚本的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持得得之家。
本文标题为:C#使用IronPython库调用Python脚本


基础教程推荐
- C#中的Linq to JSON操作详解 2023-06-08
- Unity 如何获取鼠标停留位置下的物体 2023-04-10
- C# 解析XML和反序列化的示例 2023-04-14
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- C#中 Json 序列化去掉null值的方法 2022-11-18
- C#调用摄像头实现拍照功能的示例代码 2023-03-09
- Unity shader实现高斯模糊效果 2023-01-16
- 实例详解C#实现http不同方法的请求 2022-12-26
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20