C#调用Python脚本及使用Python的第三方模块
Write By CS逍遥剑仙
我的主页: csxiaoyao.com
GitHub: github.com/csxiaoyaojianxian
Email: sunjianfeng@csxiaoyao.com
QQ: 1724338257
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