最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python通過clr庫實(shí)現(xiàn)與.NET互操作教程

 更新時(shí)間:2025年11月13日 08:30:15   作者:學(xué)亮編程手記  
本文詳細(xì)介紹了Python的clr庫,用于在Python和.NET之間進(jìn)行互操作,內(nèi)容涵蓋了安裝配置、程序集加載、類型轉(zhuǎn)換、對(duì)象操作、事件處理、異常處理以及高級(jí)功能等,通過實(shí)際應(yīng)用案例,展示了如何在Python中利用.NET生態(tài)系統(tǒng),需要的朋友可以參考下

Pythonclr庫使用詳解

clrpythonnet 包提供的模塊,用于在 Python 和 .NET 之間進(jìn)行互操作。

1. 安裝和基礎(chǔ)配置

安裝

pip install pythonnet

基礎(chǔ)導(dǎo)入

import clr
import sys
import os

2. 加載 .NET 程序集

方法一:加載 GAC 中的程序集

import clr

# 加載系統(tǒng)程序集
clr.AddReference("System")
clr.AddReference("System.Core")
clr.AddReference("System.Data")
clr.AddReference("System.Windows.Forms")

from System import *
from System.IO import *
from System.Diagnostics import *

方法二:加載特定版本程序集

import clr

# 加載特定版本
clr.AddReference("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")

# 或者使用 LoadFrom
clr.AddReferenceByName("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")

方法三:加載本地 DLL 文件

import clr
import os

# 添加 DLL 搜索路徑
clr.AddReference("YourAssembly")  # 如果 DLL 在 Python 路徑中

# 或者指定完整路徑
clr.AddReferenceToFile(r"C:\path\to\YourAssembly.dll")

# 或者使用 LoadFrom
clr.AddReferenceToFileAndPath(r"C:\path\to\YourAssembly.dll")

# 添加整個(gè)目錄到搜索路徑
clr.AddReference(".")  # 當(dāng)前目錄

3. 基本類型轉(zhuǎn)換

數(shù)值類型

import clr
from System import *

# Python 到 .NET
int_value = Int32(42)
double_value = Double(3.14)
bool_value = Boolean(True)

# .NET 到 Python
python_int = int(int_value)
python_float = float(double_value)
python_bool = bool(bool_value)

print(f".NET Int32: {int_value}, Python int: {python_int}")
print(f".NET Double: {double_value}, Python float: {python_float}")

字符串處理

import clr
from System import *

# 字符串轉(zhuǎn)換
net_string = String("Hello from .NET")
python_string = str(net_string)

# 字符串操作
net_string = String("Hello World")
length = net_string.Length                    # 屬性訪問
substring = net_string.Substring(0, 5)       # 方法調(diào)用
contains = net_string.Contains("Hello")      # 布爾方法

print(f"Length: {length}")
print(f"Substring: {substring}")
print(f"Contains 'Hello': {contains}")

數(shù)組和集合

import clr
from System import *

# 創(chuàng)建 .NET 數(shù)組
int_array = Array.CreateInstance(Int32, 5)
for i in range(5):
    int_array[i] = i * 10

# 或者使用更簡單的方法
from System import Array
int_array2 = Array[int]([1, 2, 3, 4, 5])

# 列表轉(zhuǎn)換
from System.Collections.Generic import List
net_list = List[int]()
net_list.Add(1)
net_list.Add(2)
net_list.Add(3)

# Python 列表到 .NET 列表
python_list = [10, 20, 30]
net_list_from_python = List[int](python_list)

print(f".NET 數(shù)組: {[x for x in int_array]}")
print(f".NET 列表: {[x for x in net_list]}")

4. 創(chuàng)建和使用 .NET 對(duì)象

實(shí)例化對(duì)象

import clr
from System import *
from System.IO import *
from System.Text import *

# 創(chuàng)建各種對(duì)象
sb = StringBuilder()
sb.Append("Hello")
sb.Append(" World")
result = sb.ToString()

# 使用 FileInfo
file_info = FileInfo("test.txt")
print(f"文件存在: {file_info.Exists}")
print(f"文件擴(kuò)展名: {file_info.Extension}")

# 使用 DateTime
now = DateTime.Now
tomorrow = now.AddDays(1)
time_span = tomorrow - now

print(f"現(xiàn)在: {now}")
print(f"明天: {tomorrow}")
print(f"時(shí)間差: {time_span.TotalHours} 小時(shí)")

調(diào)用靜態(tài)方法和屬性

import clr
from System import *
from System.Math import *
from System.Environment import *

# 靜態(tài)方法
max_value = Max(10, 20)
sqrt_value = Sqrt(16.0)
pi_value = PI

# 靜態(tài)屬性
machine_name = MachineName
os_version = OSVersion
current_directory = CurrentDirectory

print(f"Math.Max(10, 20) = {max_value}")
print(f"Math.Sqrt(16) = {sqrt_value}")
print(f"PI = {pi_value}")
print(f"機(jī)器名: {machine_name}")
print(f"操作系統(tǒng): {os_version}")
print(f"當(dāng)前目錄: {current_directory}")

5. 事件處理

訂閱 .NET 事件

import clr
from System import *
from System.Timers import *

class TimerHandler:
    def __init__(self):
        self.count = 0
    
    def OnTimerElapsed(self, sender, e):
        self.count += 1
        print(f"定時(shí)器觸發(fā) {self.count} 次 - {DateTime.Now}")

# 創(chuàng)建定時(shí)器
timer = Timer(1000)  # 1秒間隔
handler = TimerHandler()

# 訂閱事件
timer.Elapsed += handler.OnTimerElapsed
timer.Start()

print("定時(shí)器已啟動(dòng),按 Enter 停止...")
input()
timer.Stop()

使用委托

import clr
from System import *

# 定義委托處理程序
def message_handler(message):
    print(f"收到消息: {message}")

# 使用 Action 委托
action_delegate = Action[str](message_handler)
action_delegate.Invoke("Hello from delegate!")

# 使用 Func 委托
def add_numbers(a, b):
    return a + b

func_delegate = Func[int, int, int](add_numbers)
result = func_delegate.Invoke(5, 3)
print(f"5 + 3 = {result}")

6. 異常處理

捕獲 .NET 異常

import clr
from System import *
from System.IO import *

def file_operations():
    try:
        # 嘗試讀取不存在的文件
        file_content = File.ReadAllText("nonexistent_file.txt")
        print(file_content)
        
    except FileNotFoundException as e:
        print(f"文件未找到異常: {e.Message}")
        
    except UnauthorizedAccessException as e:
        print(f"訪問被拒絕: {e.Message}")
        
    except Exception as e:  # 捕獲所有 .NET 異常
        print(f"其他異常: {e.GetType().Name}: {e.Message}")

def division_operations():
    try:
        from System import DivideByZeroException
        result = 10 / 0
        
    except DivideByZeroException as e:
        print(f"除零異常: {e.Message}")
        
    except Exception as e:
        print(f"Python 異常: {e}")

if __name__ == "__main__":
    file_operations()
    division_operations()

7. 高級(jí)功能

反射和動(dòng)態(tài)調(diào)用

import clr
from System import *
from System.Reflection import *

class ReflectionDemo:
    def explore_assembly(self, assembly_name):
        # 加載程序集
        clr.AddReference(assembly_name)
        assembly = Assembly.Load(assembly_name)
        
        print(f"程序集: {assembly.FullName}")
        print("類型列表:")
        
        for type_obj in assembly.GetTypes():
            if type_obj.IsPublic:
                print(f"  {type_obj.FullName}")
                
                # 顯示方法
                methods = type_obj.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
                for method in methods[:3]:  # 只顯示前3個(gè)方法
                    print(f"    方法: {method.Name}")

# 使用示例
demo = ReflectionDemo()
demo.explore_assembly("System")

泛型使用

import clr
from System import *
from System.Collections.Generic import *

def generic_collections():
    # 創(chuàng)建泛型字典
    dictionary = Dictionary[str, int]()
    dictionary["one"] = 1
    dictionary["two"] = 2
    dictionary["three"] = 3
    
    # 遍歷字典
    for kvp in dictionary:
        print(f"Key: {kvp.Key}, Value: {kvp.Value}")
    
    # 泛型列表
    list_of_strings = List[str]()
    list_of_strings.Add("Apple")
    list_of_strings.Add("Banana")
    list_of_strings.Add("Cherry")
    
    # 使用 LINQ (需要引用 System.Linq)
    try:
        clr.AddReference("System.Core")
        from System.Linq import Enumerable
        
        filtered = Enumerable.Where(list_of_strings, lambda x: x.startswith("A"))
        print("以 A 開頭的項(xiàng)目:")
        for item in filtered:
            print(f"  {item}")
            
    except Exception as e:
        print(f"LINQ 不可用: {e}")

if __name__ == "__main__":
    generic_collections()

多線程編程

import clr
from System import *
from System.Threading import *
from System.ComponentModel import *

class BackgroundWorkerDemo:
    def __init__(self):
        self.worker = BackgroundWorker()
        self.worker.WorkerReportsProgress = True
        self.worker.WorkerSupportsCancellation = True
        
        self.worker.DoWork += self.on_do_work
        self.worker.ProgressChanged += self.on_progress_changed
        self.worker.RunWorkerCompleted += self.on_work_completed
    
    def on_do_work(self, sender, e):
        worker = sender
        for i in range(1, 101):
            if worker.CancellationPending:
                e.Cancel = True
                return
            
            Thread.Sleep(50)  # 模擬工作
            worker.ReportProgress(i, f"處理項(xiàng)目 {i}")
    
    def on_progress_changed(self, sender, e):
        print(f"進(jìn)度: {e.ProgressPercentage}% - {e.UserState}")
    
    def on_work_completed(self, sender, e):
        if e.Cancelled:
            print("操作被取消")
        elif e.Error:
            print(f"發(fā)生錯(cuò)誤: {e.Error.Message}")
        else:
            print("操作完成!")
    
    def start(self):
        self.worker.RunWorkerAsync()
    
    def cancel(self):
        self.worker.CancelAsync()

# 使用示例
demo = BackgroundWorkerDemo()
demo.start()

print("后臺(tái)工作已啟動(dòng),按 Enter 取消...")
input()
demo.cancel()

8. 實(shí)際應(yīng)用案例

案例1:文件監(jiān)控

import clr
from System import *
from System.IO import *

class FileMonitor:
    def __init__(self, path):
        self.watcher = FileSystemWatcher()
        self.watcher.Path = path
        self.watcher.IncludeSubdirectories = True
        
        # 訂閱事件
        self.watcher.Created += self.on_file_created
        self.watcher.Changed += self.on_file_changed
        self.watcher.Deleted += self.on_file_deleted
        self.watcher.Renamed += self.on_file_renamed
    
    def on_file_created(self, sender, e):
        print(f"文件創(chuàng)建: {e.FullPath}")
    
    def on_file_changed(self, sender, e):
        print(f"文件修改: {e.FullPath}")
    
    def on_file_deleted(self, sender, e):
        print(f"文件刪除: {e.FullPath}")
    
    def on_file_renamed(self, sender, e):
        print(f"文件重命名: {e.OldFullPath} -> {e.FullPath}")
    
    def start(self):
        self.watcher.EnableRaisingEvents = True
        print(f"開始監(jiān)控目錄: {self.watcher.Path}")
    
    def stop(self):
        self.watcher.EnableRaisingEvents = False
        print("停止監(jiān)控")

# 使用示例
monitor = FileMonitor(".")
monitor.start()

print("文件監(jiān)控已啟動(dòng),按 Enter 停止...")
input()
monitor.stop()

案例2:Windows 服務(wù)交互

import clr
from System import *
from System.ServiceProcess import *

class ServiceManager:
    def list_services(self):
        services = ServiceController.GetServices()
        print("系統(tǒng)服務(wù)列表:")
        for service in services:
            status = service.Status
            print(f"  {service.ServiceName} - {service.DisplayName} - {status}")
    
    def control_service(self, service_name, action):
        try:
            service = ServiceController(service_name)
            
            if action == "start":
                if service.Status == ServiceControllerStatus.Stopped:
                    service.Start()
                    service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(30))
                    print(f"服務(wù) {service_name} 已啟動(dòng)")
                else:
                    print(f"服務(wù) {service_name} 不是停止?fàn)顟B(tài)")
            
            elif action == "stop":
                if service.Status == ServiceControllerStatus.Running:
                    service.Stop()
                    service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(30))
                    print(f"服務(wù) {service_name} 已停止")
                else:
                    print(f"服務(wù) {service_name} 不是運(yùn)行狀態(tài)")
            
            elif action == "restart":
                if service.Status == ServiceControllerStatus.Running:
                    service.Stop()
                    service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(30))
                    service.Start()
                    service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(30))
                    print(f"服務(wù) {service_name} 已重啟")
                else:
                    print(f"服務(wù) {service_name} 不是運(yùn)行狀態(tài)")
                    
        except Exception as e:
            print(f"操作服務(wù)時(shí)出錯(cuò): {e}")

# 使用示例
manager = ServiceManager()
manager.list_services()

# 注意:需要管理員權(quán)限
# manager.control_service("Themes", "stop")

9. 調(diào)試和故障排除

調(diào)試技巧

import clr
from System import *
import traceback

def debug_net_interop():
    try:
        # 查看已加載的程序集
        print("已加載的程序集:")
        for assembly in clr.ListAssemblies():
            print(f"  {assembly}")
        
        # 檢查類型信息
        clr.AddReference("System")
        from System import String
        
        string_type = type(String("test"))
        print(f"String 類型: {string_type}")
        print(f"String 方法: {[method for method in dir(String) if not method.startswith('_')][:5]}")
        
    except Exception as e:
        print(f"調(diào)試過程中出錯(cuò): {e}")
        traceback.print_exc()

def memory_management():
    """內(nèi)存管理示例"""
    import gc
    
    # 創(chuàng)建大量 .NET 對(duì)象
    objects = []
    for i in range(1000):
        sb = StringBuilder()
        sb.Append(f"String {i}")
        objects.append(sb)
    
    print(f"創(chuàng)建了 {len(objects)} 個(gè)對(duì)象")
    
    # 強(qiáng)制垃圾回收
    gc.collect()
    print("垃圾回收完成")

if __name__ == "__main__":
    debug_net_interop()
    memory_management()

10. 性能優(yōu)化建議

import clr
from System import *
import time

class PerformanceOptimizer:
    @staticmethod
    def benchmark_operations():
        """性能基準(zhǔn)測(cè)試"""
        from System.Text import StringBuilder
        
        # 測(cè)試字符串拼接性能
        start_time = time.time()
        
        # 方法1:使用 Python 字符串拼接
        result1 = ""
        for i in range(10000):
            result1 += str(i)
        
        time1 = time.time() - start_time
        
        # 方法2:使用 .NET StringBuilder
        start_time = time.time()
        sb = StringBuilder()
        for i in range(10000):
            sb.Append(str(i))
        result2 = sb.ToString()
        
        time2 = time.time() - start_time
        
        print(f"Python 字符串拼接: {time1:.4f} 秒")
        print(f".NET StringBuilder: {time2:.4f} 秒")
        print(f"性能提升: {time1/time2:.2f}x")

    @staticmethod
    def batch_operations():
        """批量操作優(yōu)化"""
        from System.Collections.Generic import List
        
        # 不推薦的寫法:逐個(gè)添加
        slow_list = List[int]()
        start_time = time.time()
        for i in range(10000):
            slow_list.Add(i)
        slow_time = time.time() - start_time
        
        # 推薦的寫法:批量添加
        fast_list = List[int]()
        start_time = time.time()
        fast_list.AddRange(range(10000))
        fast_time = time.time() - start_time
        
        print(f"逐個(gè)添加: {slow_time:.4f} 秒")
        print(f"批量添加: {fast_time:.4f} 秒")
        print(f"性能提升: {slow_time/fast_time:.2f}x")

if __name__ == "__main__":
    PerformanceOptimizer.benchmark_operations()
    PerformanceOptimizer.batch_operations()

總結(jié)

clr 庫提供了強(qiáng)大的 Python 與 .NET 互操作能力:

  1. 程序集加載:支持 GAC、本地文件等多種方式
  2. 類型轉(zhuǎn)換:自動(dòng)處理基本類型轉(zhuǎn)換
  3. 對(duì)象操作:創(chuàng)建實(shí)例、調(diào)用方法、訪問屬性 
  4. 事件處理:訂閱 .NET 事件和委托
  5. 異常處理:捕獲和處理 .NET 異常
  6. 高級(jí)特性:反射、泛型、多線程支持

使用時(shí)的注意事項(xiàng):

  • 確保架構(gòu)匹配(x86/x64)
  • 處理內(nèi)存管理
  • 注意性能優(yōu)化
  • 適當(dāng)處理異常

這個(gè)庫使得在 Python 中利用豐富的 .NET 生態(tài)系統(tǒng)成為可能。

以上就是Python使用clr庫實(shí)現(xiàn)與.NET互操作教程的詳細(xì)內(nèi)容,更多關(guān)于Python clr與.NET互操作的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 如何基于python生成list的所有的子集

    如何基于python生成list的所有的子集

    這篇文章主要介紹了如何基于python生成list的所有的子集,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-11-11
  • Linux下Python獲取IP地址的代碼

    Linux下Python獲取IP地址的代碼

    這篇文章主要介紹了Linux下Python獲取IP地址的代碼,需要的朋友可以參考下
    2014-11-11
  • python+selenium+chrome實(shí)現(xiàn)淘寶購物車秒殺自動(dòng)結(jié)算

    python+selenium+chrome實(shí)現(xiàn)淘寶購物車秒殺自動(dòng)結(jié)算

    這篇文章主要介紹了python+selenium+chrome實(shí)現(xiàn)淘寶購物車秒殺自動(dòng)結(jié)算,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-01-01
  • Python中使用Flask、MongoDB搭建簡易圖片服務(wù)器

    Python中使用Flask、MongoDB搭建簡易圖片服務(wù)器

    這篇文章主要介紹了Python中使用Flask、MongoDB搭建簡易圖片服務(wù)器,本文是一個(gè)詳細(xì)完整的教程,需要的朋友可以參考下
    2015-02-02
  • Python通過PyMuPDF高效處理PDF文檔的操作方法

    Python通過PyMuPDF高效處理PDF文檔的操作方法

    PyMuPDF(又稱 fitz)是一個(gè)功能強(qiáng)大的Python庫,用于處理PDF、XPS、EPUB、MOBI等文檔格式,它基于MuPDF(輕量級(jí) PDF 渲染引擎),提供高效的文本提取、渲染、編輯和文檔分析功能,所以本文給大家介紹了Python通過PyMuPDF高效處理PDF文檔的操作方法
    2025-11-11
  • Python環(huán)境搭建之OpenCV的步驟方法

    Python環(huán)境搭建之OpenCV的步驟方法

    本篇文章主要介紹了Python環(huán)境搭建之OpenCV的步驟方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-10-10
  • opencv深入淺出了解機(jī)器學(xué)習(xí)和深度學(xué)習(xí)

    opencv深入淺出了解機(jī)器學(xué)習(xí)和深度學(xué)習(xí)

    機(jī)器學(xué)習(xí)是人工智能的核心,專門研究如何讓計(jì)算機(jī)模擬和學(xué)習(xí)人類的行為。?深度學(xué)習(xí)是機(jī)器學(xué)習(xí)中的一個(gè)熱門研究方向,它主要研究樣本數(shù)據(jù)的內(nèi)在規(guī)律和表示層次,讓計(jì)算機(jī)能夠讓人一樣具有分析與學(xué)習(xí)能力
    2022-03-03
  • 使用python實(shí)現(xiàn)數(shù)組、鏈表、隊(duì)列、棧的方法

    使用python實(shí)現(xiàn)數(shù)組、鏈表、隊(duì)列、棧的方法

    數(shù)據(jù)結(jié)構(gòu)是指相互之間存在著一種或多種關(guān)系的數(shù)據(jù)元素的集合和該集合中數(shù)據(jù)元素之間的關(guān)系組成。這篇文章主要介紹了使用python實(shí)現(xiàn)數(shù)組、鏈表、隊(duì)列、棧的相關(guān)知識(shí),需要的朋友可以參考下
    2019-12-12
  • Python中批量文件處理與自動(dòng)化管理技巧分享

    Python中批量文件處理與自動(dòng)化管理技巧分享

    在日常辦公或數(shù)據(jù)處理工作中,我們經(jīng)常需要處理大量的文件,本文主要介紹了如何使用Python進(jìn)行文件操作,目錄管理等常見任務(wù),希望對(duì)大家有所幫助
    2025-02-02
  • Python 正則表達(dá)式的高級(jí)用法

    Python 正則表達(dá)式的高級(jí)用法

    作為一個(gè)概念而言,正則表達(dá)式對(duì)于Python來說并不是獨(dú)有的。但是,Python中的正則表達(dá)式在實(shí)際使用過程中還是有一些細(xì)小的差別。本文是一系列關(guān)于Python正則表達(dá)式文章的其中一部分。
    2016-12-12

最新評(píng)論

偏关县| 长垣县| 曲水县| 高淳县| 东莞市| 福建省| 泾源县| 柘荣县| 镇安县| 城步| 滦南县| 邯郸县| 新源县| 永寿县| 卓尼县| 陇川县| 姚安县| 宜都市| 荔浦县| 博罗县| 宁国市| 丹巴县| 阳山县| 阿城市| 曲靖市| 峡江县| 于田县| 海宁市| 锦州市| 青神县| 六安市| 浦北县| 馆陶县| 大丰市| 闽侯县| 新昌县| 厦门市| 通榆县| 大庆市| 五台县| 阳山县|