好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

C#调用python文件执行

我的电脑环境是使用.net framework4.5.1,如果在调试过程中调不通请注意

我用的是visual studion 2017,python组件下载地址:http://ironpython.codeplex.com/releases/view/

下载的版本是2.7,下载安装完之后记得引入安装路径下的以下三个dll

 (1)首先先说一个简单的功能,在c#代码中执行python字符串,内容如下:   

 (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" );

结果如下:

调用成功.

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

dy("nrwz");

查看更多关于C#调用python文件执行的详细内容...

  阅读:41次