iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >C#使用IronPython库调用Python脚本
  • 361
分享到

C#使用IronPython库调用Python脚本

2024-04-02 19:04:59 361人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

Ironpython是一种在 .net及 Mono上的 Python实现,由微软的 Jim Hugunin所发起,是一个开源的项目,基于微软的 DLR引擎。 IronPython的主

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脚本的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持编程网。

--结束END--

本文标题: C#使用IronPython库调用Python脚本

本文链接: https://www.lsjlt.com/news/151220.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • C#使用IronPython库调用Python脚本
    IronPython是一种在 .NET及 Mono上的 Python实现,由微软的 Jim Hugunin所发起,是一个开源的项目,基于微软的 DLR引擎。 IronPython的主...
    99+
    2024-04-02
  • C#中怎么使用IronPython库调用Python脚本
    在C#中使用IronPython库调用Python脚本的步骤如下: 首先,需要将IronPython库添加到C#项目中。可以通过...
    99+
    2024-03-08
    python C#
  • C#使用IronPython调用Python的实现
    目录一、前言二、IronPython安装配置三、基础使用及标准库使用1、创建python脚本2、调用脚本四、IronPython调用第三方库1、创建python虚拟环境2、pytho...
    99+
    2023-02-08
    C# IronPython调用Python IronPython调用Python
  • c#(IronPython)调用Pyth
    直接一段代码演示 public void StartTCP() { ScriptEngine engine = Python.CreateEngine(); var pat...
    99+
    2023-01-30
    IronPython Pyth
  • C#如何调用python脚本
    目录C#调用python脚本方式一方式二方式三方式四方式五C#调用python脚本 在平常工程项目开发过程中常常会涉及到机器学习、深度学习算法方面的开发任务,但是受限于程序设计语言本...
    99+
    2024-04-02
  • C++中怎么调用Python脚本
    C++中怎么调用Python脚本,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。#test function   def add...
    99+
    2023-06-17
  • C++中怎么调用python脚本函数
    本篇文章给大家分享的是有关C++中怎么调用python脚本函数,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。C++调用python脚本函数代码如下:Py_Initialize(...
    99+
    2023-06-17
  • jmeter调用python脚本 入
    参考文章1; Jmeter 运行 Python 代码进行 AK/SK 认证 (使用 OS Process Sampler) 思路是;jmeter调用shell,用shell执行py   参考文章2:  Jmeter执行python脚本函数...
    99+
    2023-01-31
    脚本 jmeter python
  • golang怎么调用python脚本
    在Golang中调用Python脚本可以使用os/exec包来执行外部命令。下面是一个简单的示例代码:gopackage maini...
    99+
    2023-10-20
    golang python
  • 在java中调用python脚本
    在java中调用python脚本 推荐使用第三种方法,因为只有第三种方法使用Runtime.getRuntime()才能执行含有第三方库(numpy,matlab,pandas等库)的python脚本...
    99+
    2023-09-07
    python java numpy
  • go怎么调用python脚本
    要在Go语言中调用Python脚本,可以使用os/exec包中的Command函数来执行Python脚本。 以下是一个简单的示例代码...
    99+
    2023-10-23
    go python
  • django怎么调用python脚本
    要在Django中调用Python脚本,可以按照以下步骤进行操作:1. 在Django项目的根目录下创建一个名为`scripts`的...
    99+
    2023-10-10
    django python
  • python调用C库
    编写C库test.c#include <stdio.h> #include <string.h> int strcmpTest(char *a, char *b) { return strcmp(a,...
    99+
    2023-01-31
    python
  • C语言中程序如何调用Python脚本
    目录一、环境配置0x00 平台0x01 添加 包含目录 和 库目录0x02 添加依赖项二、案例三、常用API有时候在写C语言程序的时候又想利用一下pyt...
    99+
    2024-04-02
  • Jmeter如何使用BeanShell取样器调用Python脚本
    1、在线程组中按以下方式添加【BeanShell取样器】: 2、把以下这段代码放到【BeanShell取样器】的脚本区域:  注意点: (1)命令里的Python脚本路径...
    99+
    2024-04-02
  • python调用bash shell脚本方法
    目录1. os.system()1.1. demo2. os.popen()2.1 demo3. commands模块4. subprocess4.1 demo1. os.syste...
    99+
    2024-04-02
  • Shell脚本里调用Python程序
    脚本背景:主管要求看门狗程序不仅仅只是看门,还要在看门成功的时候发送邮件给各个开发人员,而且必须要用公司原有的python程序作为发送邮件的主程序,所以需要在原有的看门狗程序上加一句话,而这个看门狗程序恰恰是shell程序,两种不同程序混搭...
    99+
    2023-01-31
    脚本 程序 Shell
  • shell中如何调用python脚本
    要在shell中调用Python脚本,可以使用以下命令:```python script.py```其中,`python`是Pyth...
    99+
    2023-10-10
    shell python
  • python直接调用和使用swig法方调用c++库
    c++运算速度快于python,python简单易写。很多时候对于已有的c++代码也不想用python重写,此时就自然而然地想到用python调用c或者c++,两全其美。然而根据这些...
    99+
    2024-04-02
  • 在node中如何调用python脚本
    目录node调用python脚本使用场景1、准备运行环境,获取python路径2、前端把命令字符串和python路径传给后端3、服务端调用python脚本nodejs调用python...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作