官网为:IronPython.net /
环境配置
1、使用visual studio2022创建一个控制台项目 2、打开Nuget管理工具,搜索IronPython
3、记得安装vs的python支持,避免编译失败情况 4、在项目中创建一个PythonScripts的文件夹,用来存放python代码
简单调用
我们可以简单编写程序如下
python
# main.py
import sys
import uuid
def Test():
return 'Hello IronPython!'
def SysVersion():
return sys.version
def CreateUUID():
return str(uuid.uuid1())
def Print():
print('Hello World!')
这时在Program.cs中可以输入如下
C#
using System;
using IronPython.Hosting;
var engine = Python.CreateEngine();
dynamic py = engine.ExecuteFile(@"PythonScripts/main.py");
Console.WriteLine("Test:");
var data = py.Test();
Console.WriteLine(data);
Console.WriteLine();
Console.WriteLine("Python & .NET Version:");
var version = py.SysVersion();
Console.WriteLine(version);
Console.WriteLine();
// 使用Python的UUID标准库生成基于时间戳的UUID
Console.WriteLine("Create UUID By Python:");
var uuid = py.CreateUUID();
Console.WriteLine(uuid.ToString());
Console.WriteLine();
var print = py.Print();
如何获取main中变量的值并更改
python
# main.py
import sys
import uuid
a=10
def Test():
return 'Hello IronPython!'
def SysVersion():
return sys.version
def CreateUUID():
return str(uuid.uuid1())
def Print():
print('Hello World!')
设置a等于10
C#
var a = py.GetVariable("a");
Console.WriteLine("a的值为"+a.ToString());
py.SetVariable("a", 20);
var v = py.GetVariable("a");
Console.WriteLine("a修改后的值为"+v.ToString());
那如何调用函数并传值呢?
python
import sys
import uuid
a=10
def Test():
return 'Hello IronPython!'
def SysVersion():
return sys.version
def CreateUUID():
return str(uuid.uuid1())
def Print():
print('Hello World!')
def add_numbers(a,b):
return a + b
C#
using System;
using IronPython.Hosting;
var engine = Python.CreateEngine();
dynamic py = engine.ExecuteFile(@"PythonScripts/main.py");
Console.WriteLine("Test:");
var data = py.Test();
Console.WriteLine(data);
Console.WriteLine();
Console.WriteLine("Python & .NET Version:");
var version = py.SysVersion();
Console.WriteLine(version);
Console.WriteLine();
// 使用Python的UUID标准库生成基于时间戳的UUID
Console.WriteLine("Create UUID By Python:");
var uuid = py.CreateUUID();
Console.WriteLine(uuid.ToString());
Console.WriteLine();
var print = py.Print();
var a = py.GetVariable("a");
Console.WriteLine("a的值为"+a.ToString());
py.SetVariable("a", 20);
var v = py.GetVariable("a");
Console.WriteLine("a修改后的值为"+v.ToString());
var add_function = py.GetVariable("add_numbers");
int a1 = 5;
int b1 = 3;
var res = add_function(a1, b1);
Console.WriteLine(res);
结果为: