共計 755 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 C# 中使用 IronPython 庫調用 Python 腳本的步驟如下:
-
首先,需要將 IronPython 庫添加到 C# 項目中??梢酝ㄟ^ NuGet 包管理器搜索 IronPython,并將其添加到項目中。
-
創建一個 Python 腳本文件,編寫需要調用的 Python 代碼。例如,創建一個名為 "hello.py" 的 Python 腳本文件,內容如下:
def say_hello(name):
return "Hello, " + name + "!"
- 在 C# 代碼中,使用 IronPython 庫加載并執行 Python 腳本。以下是一個示例代碼:
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
class Program
{static void Main()
{// 創建 Python 運行時環境
var engine = Python.CreateEngine();
var scope = engine.CreateScope();
// 加載 Python 腳本文件
engine.ExecuteFile("hello.py", scope);
// 調用 Python 函數
dynamic say_hello = scope.GetVariable("say_hello");
var result = say_hello("Alice");
Console.WriteLine(result); // 輸出:Hello, Alice!
}
}
在這個示例中,首先創建了 Python 運行時環境和一個作用域對象。然后使用 ExecuteFile
方法加載了 "hello.py" 腳本文件,并通過作用域對象獲取了 Python 函數 "say_hello" 并調用它。
通過以上步驟,就可以在 C# 中使用 IronPython 庫調用 Python 腳本了。
丸趣 TV 網 – 提供最優質的資源集合!
正文完