首页 技术 正文
技术 2022年11月9日
0 收藏 603 点赞 2,870 浏览 1714 个字

最近因为项目设计,有部分使用Python脚本,因此代码中需要调用python方法。

1.首先,在c#中调用python必须安装IronPython,在 http://ironpython.codeplex.com/  中下载

2.对应用程序添加IronPython.dll和Microsoft.Scripting.dll 的引用

C#中调用python方法

3.调用python:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;namespace WpfUsingPythonDemo
{
public class UsingPython
{
private ScriptRuntime pyRuntime = null;
private dynamic obj = null;
public UsingPython()
{
string serverpath = AppDomain.CurrentDomain.BaseDirectory + "frs_main.py";//所引用python路径
pyRuntime = Python.CreateRuntime();
ScriptEngine Engine = pyRuntime.GetEngine("python");
ScriptScope pyScope = Engine.CreateScope(); //Python.ImportModule(Engine, "random");
obj = Engine.ExecuteFile(serverpath, pyScope);
}
public bool ExcutePython()
{
try
{
if (null != obj)
{
obj.frs_init();//调用frs_main.py中的方法
}
else
{
return false;
}
return true;
}
catch(Exception ex)
{
throw ex;
}
}
}
}

Using Python

4.c#中引用的python应该是IronPython,与CPython版本和模块中有差别,所以需要注意使用版本

5.因为所使用的python文件中引用了很多模块,所以运行时会找不到python库,在网上查了一下,需要引入搜索路径并且引入库,如下:

 public  UsingPython()
{
string serverpath = AppDomain.CurrentDomain.BaseDirectory + "frs_main.py";//所引用python路径
pyRuntime = Python.CreateRuntime();
ScriptEngine Engine = pyRuntime.GetEngine("python");
       
      
       //手动设置搜索路径
ICollection<string> Paths = Engine.GetSearchPaths();
Paths.Add("//Lib");
Paths.Add("//Lib//site-packages");
Paths.Add(AppDomain.CurrentDomain.BaseDirectory + "frs");
//importpy文件中的库,需要注意先后引用顺序
Engine.ImportModule("sys");
Engine.ImportModule("logging");
Engine.ImportModule("Queue");
Engine.ImportModule("ctypes");
Engine.ImportModule("json");
Engine.ImportModule("os"); ScriptScope pyScope = Engine.CreateScope(); //Python.ImportModule(Engine, "random");
obj = Engine.ExecuteFile(serverpath, pyScope);
}

  这是自己摸索找到的解决方案,希望以后可以有更好的方法。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,488
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,903
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,736
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,488
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,127
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,289