C#调用Python脚本及使用Python的第三方模块

C#调用Python脚本及使用Python的第三方模块

我的主页 www.csxiaoyao.com

  IronPython是一种在.NET上实现的Python语言,使用IronPython就可以在.NET环境中调用Python代码。

【添加引用库】

  在Visual Studio新建一个工程后,添加引用IronPython.dll和Microsoft.Scripting.dll(位于IronPython的安装目录下)。

【C#代码内嵌Python】

  最简单的使用方式如下:

var engine = IronPython.Hosting.Python.CreateEngine();
engine.CreateScriptSourceFromString("print 'hello world!'").Execute();

【从文件中加载Python代码】

  一般情况下我们还是要把Python代码单独写在文件中。在工程中新建一个Python文件,如hello.py,直接建立在发布路径下即可(也可设置其属性Copy to Output Directory的值为Copy if newer)。在hello.py下编写如下代码:

#无返回值函数
def say_hello():
    print "hello!"
#有返回值函数
def get_text():
    return "text from hello.py"
#带参函数
def add(arg1, arg2):
    return arg1 + arg2

  C#代码如下:

//运行python脚本
var engine = IronPython.Hosting.Python.CreateEngine();
var scope = engine.CreateScope();
var source = engine.CreateScriptSourceFromFile("hello.py");
source.Execute(scope);
//调用无返回值函数
var say_hello = scope.GetVariable<Func<object>>("say_hello");
say_hello();
//调用有返回值函数
var get_text = scope.GetVariable<Func<object>>("get_text");
var text = get_text().ToString();
Console.WriteLine(text);
//调用带参函数
var add = scope.GetVariable<Func<object, object, object>>("add");
var result = add(1, 2);
Console.WriteLine(result);

【使用Python安装的第三模块】

  python的自带库可以直接在脚本中调用,然而第三方库直接调用会出现以下错误(调用第三方RSA):

An unhandled exception of type 'IronPython.Runtime.Exceptions.ImportException' occurred in Microsoft.Dynamic.dll
Additional information: No module named rsa

  显示没有找到模块,设置sys.path即可,如下:

import sys
sys.path.append('C:\\Python27\\lib')
sys.path.append('C:\\Python27\\lib\\site-packages\\setuptools-12.0.3-py2.7.egg')
sys.path.append('C:\\Python27\\lib\\site-packages\\rsa-3.1.1-py2.7.egg')
import rsa
  • 1
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值