C#呼叫IronPython動態執行Python程式碼

wzwyc發表於2024-08-08

安裝

Install-Package IronPython

示例程式碼

using IronPython.Hosting;

string pythonCode = @"
def sumex(numbers):
    return sum(numbers)

numbers = [1, 2, 3, 4, 5]
result = sumex(numbers)";

var engine = Python.CreateEngine();
var scope = engine.CreateScope();
engine.Execute(pythonCode, scope);
var result = scope.GetVariable("result");
var resultText = $"計算結果:{result}";

Console.WriteLine(resultText);

相關文章