zoukankan      html  css  js  c++  java
  • C#调用Python脚本的简单示例

    

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

    IronPython的在CodePlex上的主页:http://ironpython.codeplex.com/

    方式一:适用于python脚本中不包含第三方模块的情况

    1、执行语句

    借由IronPython,就可以利用.NET执行存储在Python脚本中的代码段。下面通过简单的示例说明如何应用C#调用Python脚本。

    1、在VS中新建窗体项目:IronPythonDemo

    2、VS的菜单中打开“Nuget程序包管理器”

    image

    3、搜索IronPython程序包并安装

    image

    安装后自动引用如下的DLL

    image

    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文件属性为“复制到输出目录”

    image

    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:Python2python.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("
    ".encode("utf-8"))
            time.sleep(1)
            ser.write("root
    ".encode("utf-8"))
            time.sleep(1)
            passwordStr="%s
    " % password
            ser.write(passwordStr.encode("utf-8"))
            time.sleep(1)
            ser.write("killall -9 xxx
    ".encode("utf-8"))
            time.sleep(1)
            ser.write("rm /etc/xxx/xxx_user.*
    ".encode("utf-8"))
            time.sleep(1)
            ser.write("reboot
    ".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()方式,调试有各种问题,最终放弃了,没有研究。

  • 相关阅读:
    An Empirical Evaluation of Generic Convolutional and Recurrent Networks for Sequence Modeling
    Multi-attention Network for One Shot Learning
    Visual Question Answering with Memory-Augmented Networks
    Tutorial on word2vector using GloVe and Word2Vec
    论文笔记:Tracking by Natural Language Specification
    论文笔记:Semantic Segmentation using Adversarial Networks
    论文笔记:Attention Is All You Need
    论文笔记:Capsules for Object Segmentation
    美国签证申请流程
    论文笔记:Diffusion-Convolutional Neural Networks (传播-卷积神经网络)
  • 原文地址:https://www.cnblogs.com/springsnow/p/13180518.html
Copyright © 2011-2022 走看看