欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#使用IronPython庫調(diào)用Python腳本

 更新時間:2022年06月13日 09:33:22   作者:springsnow  
這篇文章介紹了C#使用IronPython庫調(diào)用Python腳本的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

IronPython是一種在 .NET及 Mono上的 Python實(shí)現(xiàn),由微軟的 Jim Hugunin所發(fā)起,是一個開源的項(xiàng)目,基于微軟的 DLR引擎。

IronPython的主頁: IronPython.net /

github站點(diǎn):

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、執(zhí)行語句

借由IronPython,就可以利用.NET執(zhí)行存儲在Python腳本中的代碼段。下面通過簡單的示例說明如何應(yīng)用C#調(diào)用Python腳本。

1、在VS中新建窗體項(xiàng)目:IronPythonDemo

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

3、搜索IronPython程序包并安裝

安裝后自動引用如下的DLL

4、在exe程序所在文件夾下創(chuàng)建Python腳本。Python示例腳本實(shí)現(xiàn)求兩個數(shù)的四則運(yùn)算:

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

設(shè)置IronPythonDemo.py文件屬性為“復(fù)制到輸出目錄”

5、修改工程的配置文件App.config如下:

其中microsoft.scripting節(jié)點(diǎn)中設(shè)置了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、編寫計(jì)算的函數(shù):

ScriptRuntime scriptRuntime = ScriptRuntime.CreateFromConfiguration();
ScriptEngine pyEngine = scriptRuntime.GetEngine("python");
ScriptSource source = pyEngine.CreateScriptSourceFromFile("IronPythonDemo.py");//設(shè)置腳本文件
ScriptScope scope = pyEngine.CreateScope();

try
{
    //設(shè)置參數(shù)
    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、編譯運(yùn)行可得計(jì)算結(jié)果(此處未做輸入的檢查)

2、執(zhí)行函數(shù)

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();//創(chuàng)建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);//調(diào)用腳本文件中對應(yīng)的函數(shù)
MessageBox.Show(reStr);


//或者

ScriptRuntime pyRuntime = IronPython.Hosting.Python.CreateRuntime(); //創(chuàng)建一下運(yùn)行環(huán)境
dynamic obj = pyRuntime.UseFile("IronPythonDemo2.py"); //調(diào)用一個Python文件
int[] array = new int[9] { 9, 3, 5, 7, 2, 1, 3, 6, 8 };
string reStr = obj.main(array);//調(diào)用腳本文件中對應(yīng)的函數(shù)
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)//添加參數(shù)
            {
                sArguments += " " + sigstr;
            }

            p.StartInfo.FileName = @"D:\Python2\python.exe"; //python2.7的安裝路徑
            p.StartInfo.Arguments = sArguments;//python命令的參數(shù)
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.Start();//啟動進(jìn)程

            Console.WriteLine("執(zhí)行完畢!");

            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腳本實(shí)現(xiàn)的是重啟IPC設(shè)備,測試功能成功。

調(diào)用包含第三方模塊的python腳本時,嘗試過使用path.append()方式,調(diào)試有各種問題,最終放棄了,沒有研究。

到此這篇關(guān)于C#使用IronPython庫調(diào)用Python腳本的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論