源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

C#调用python文件执行

  • 时间:2020-07-30 08:41 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:C#调用python文件执行
我的电脑环境是使用.net framework4.5.1,如果在调试过程中调不通请注意 我用的是Visual studion 2017,python组件下载地址:[url=http://ironpython.codeplex.com/releases/view/]http://ironpython.codeplex.com/releases/view/[/url] 下载的版本是2.7,下载安装完之后记得引入安装路径下的以下三个dll [img]http://files.jb51.net/file_images/article/201705/2017050209165410.png[/img]  (1)首先先说一个简单的功能,在c#代码中执行python字符串,内容如下:    [img]http://files.jb51.net/file_images/article/201705/2017050209165411.png[/img]  (2)c#调用python文件: 在当前目录下新建一个后缀名为py的文件,文件名为AmoutDisc.py内容如下
dicAmt = 0.05
retAmt = amt
if amt>25:
retAmt = amt-(amt*dicAmt)
该文件定义了一个python文件,然后在c#代码中调用该python文件,给该文件传参,具体应该说给参数amt传值,最后在代码中获取python文件中的retAmt的变量值,具体代码如下:
ScriptRuntime scriptRuntime =Python.CreateRuntime();
ScriptEngine pythEng = scriptRuntime.GetEngine("Python");
ScriptSource scriptSource = pythEng.CreateScriptSourceFromFile("AmoutDisc.py");
ScriptScope scope = pythEng.CreateScope();
//scope.SetVariable("prodCount", Convert.ToInt32("34343"));
scope.SetVariable("amt", Convert.ToDecimal("434"));
scriptSource.Execute(scope);
dynamic a = scope.GetVariable("retAmt");
结果如下: [img]http://files.jb51.net/file_images/article/201705/2017050209165412.png[/img] 调用成功. 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部