C#调用Python脚本及使用Python的第三方模块
来源:互联网 发布:淘宝官网东西是真的吗 编辑:程序博客网 时间:2024/05/22 09:45
C#调用Python脚本及使用Python的第三方模块
- C调用Python脚本及使用Python的第三方模块
- 添加引用库
- C代码内嵌Python
- 从文件中加载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.dllAdditional information: No module named rsa
显示没有找到模块,设置sys.path即可,如下:
import syssys.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
0 0
- C#调用Python脚本及使用Python的第三方模块
- C#调用Python脚本并使用Python的第三方模块
- C#调用Python脚本并使用Python的第三方模块
- C#调用Python脚本并使用Python的第三方模块
- python调用第三方模块
- Jython调用不包含第三方库的python脚本
- Python:第三方模块BeautifulSoup的安装及简单用法
- Python第三方模块
- python 第三方模块
- python中使用第三方模块
- 使用easy_install安装python第三方模块的方法
- Python安装第三方模块的方法
- Python中第三方模块的安装
- 初见Python的第三方模块BeautifulSoup
- python 的yagamil第三方模块使用方法
- python第三方模块的安装
- 安装python的第三方模块
- 使用Python调用Java第三方库
- 堆排序
- 【计算机网络】TCP/IP协议三次握手与四次握手流程解析
- 在制品与前置时间(又叫交付时间)
- WRF-DA代码编译与安装(一)——依赖库的编译与安装
- Java面试中经常遇到的类执行顺序
- C#调用Python脚本及使用Python的第三方模块
- 3.2编程实现 (1)员工类(Employee)(2)部门主管类(Manager)(3)测试类(Test)
- Android安全开发之ZIP文件目录遍历
- linux下C语言my_memcopy和my_strcpy实现
- vue 请求后台数据
- Course Schedule
- 5位运动员参加了10米台跳水比赛的问题
- 我的第一篇博文
- Eclipse常用快捷键