C#调用Python脚本的简单示例

2019-12-30 12:33:06于海丽

6、 绘制窗体如下:

C#,Python脚本

7、编写计算的函数:


private void btnCalculate_Click(object sender, EventArgs e) 
  { 
   ScriptRuntime scriptRuntime = ScriptRuntime.CreateFromConfiguration(); 
   ScriptEngine rbEng = scriptRuntime.GetEngine("python"); 
   ScriptSource source = rbEng.CreateScriptSourceFromFile("IronPythonDemo.py");//设置脚本文件 
   ScriptScope scope = rbEng.CreateScope(); 
 
   try 
   { 
    //设置参数 
    scope.SetVariable("arg1",Convert.ToInt32(txtNum1.Text)); 
    scope.SetVariable("arg2", Convert.ToInt32(txtNum2.Text)); 
    scope.SetVariable("arg3", operation.SelectedIndex+1); 
   } 
   catch (Exception) 
   { 
    MessageBox.Show("输入有误。"); 
   } 
 
   source.Execute(scope); 
   labelResult.Text = scope.GetVariable("result").ToString(); 
  } 

8、编译运行可得计算结果(此处未做输入的检查)

C#,Python脚本

以上就是C#调用Python脚本的简单方法,希望对大家的学习有所帮助。



注:相关教程知识阅读请移步到c#教程频道。