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

C#使用IronPython庫調用Python腳本

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

IronPython是一種在 .NET及 Mono上的 Python實現(xiàn),由微軟的 Jim Hugunin所發(fā)起,是一個開源的項目,基于微軟的 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、執(zhí)行語句

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

1、在VS中新建窗體項目:IronPythonDemo

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

3、搜索IronPython程序包并安裝

安裝后自動引用如下的DLL

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

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節(jié)點中設置了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、編寫計算的函數(shù):

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

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

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);//調用腳本文件中對應的函數(shù)
MessageBox.Show(reStr);


//或者

ScriptRuntime pyRuntime = IronPython.Hosting.Python.CreateRuntime(); //創(chuàng)建一下運行環(huán)境
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);//調用腳本文件中對應的函數(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();//啟動進程

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

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

到此這篇關于C#使用IronPython庫調用Python腳本的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

  • C#實現(xiàn)創(chuàng)建桌面快捷方式與添加網頁到收藏夾的示例

    C#實現(xiàn)創(chuàng)建桌面快捷方式與添加網頁到收藏夾的示例

    本文是介紹了c#通過純代碼創(chuàng)建快捷方式與添加網頁到收藏夾,非常具有實用價值,有需要的朋友可以來了解一下。
    2016-10-10
  • C#使用DllImport調用非托管的代碼的方法

    C#使用DllImport調用非托管的代碼的方法

    C#調用非托管代碼的方式主要有Com調用、DllImport方式調用、加載非托管動態(tài)鏈接庫、直接執(zhí)行機器碼等方式?,F(xiàn)在介紹一下我自己常用的DllImport方式調用MSDN中提到的GetShortPathName方法;
    2013-03-03
  • DirectoryEntry配置IIS7出現(xiàn)ADSI Error:未知錯誤(0x80005000)

    DirectoryEntry配置IIS7出現(xiàn)ADSI Error:未知錯誤(0x80005000)

    這篇文章主要介紹了DirectoryEntry配置IIS7出現(xiàn)ADSI Error:未知錯誤(0x80005000)的解決辦法
    2015-09-09
  • C#中實現(xiàn)在32位、64位系統(tǒng)下自動切換不同的SQLite dll文件

    C#中實現(xiàn)在32位、64位系統(tǒng)下自動切換不同的SQLite dll文件

    這篇文章主要介紹了C#中實現(xiàn)在32位、64位系統(tǒng)下自動切換不同的SQLite dll文件,本文使用C#代碼實現(xiàn)DLL文件的切換,需要的朋友可以參考下
    2014-09-09
  • C#灰度化圖像的實例代碼

    C#灰度化圖像的實例代碼

    灰度化一幅圖像就是將圖像的色彩信息全部丟掉,將24位的位圖信息,用8位來表示,灰度圖共有256級灰度等級,也就是將24位位圖的一點如(255,255,255)轉換成255,所以R,G,B三個值所乘的系數(shù)和為1
    2013-09-09
  • 關于C#理解裝箱與拆箱

    關于C#理解裝箱與拆箱

    這篇文章主要介紹了關于C語言理解裝箱與拆箱的相關資料,需要的朋友可以參考下面文章內容
    2021-09-09
  • c#文件的I/O基本操作

    c#文件的I/O基本操作

    System.IO命名空間包含允許在數(shù)據(jù)流和文件上進行同步,異步及寫入的類型,下面是關于c#文件的I/O基本操作講解,需要的朋友可以參考下
    2014-03-03
  • 詳解WPF中用戶控件和自定義控件的使用

    詳解WPF中用戶控件和自定義控件的使用

    無論是在WPF中還是WinForm中,都有用戶控件(UserControl)和自定義控件(CustomControl),這兩種控件都是對已有控件的封裝,實現(xiàn)功能重用。但是兩者還是有一些區(qū)別,本文對這兩種控件進行講解
    2023-03-03
  • NumberToUpper數(shù)字轉中文詳解

    NumberToUpper數(shù)字轉中文詳解

    本文介紹NumberToUpper數(shù)字轉中文的方法,大家參考使用吧
    2013-12-12
  • C#?Chart?簡單使用教程

    C#?Chart?簡單使用教程

    Chart控件可以用來繪制波形圖、柱狀圖、餅圖、折線圖等,用來進行數(shù)據(jù)表現(xiàn)是很不錯的,現(xiàn)在簡單說一下這個控件的使用方法,對C#?Chart使用相關知識感興趣的朋友一起看看吧
    2022-11-11

最新評論