C#执行Python代码工具类

有时候需要C#与Python交互或者执行python写的算法,这个时候我们可以在C#中调用执行python文件形式进行交互,下面是我写的C#执行Python代码的工具类,可以直接拿来使用,需要引用IronPython.dll。

/*
     * 功能:Python与C#交互
     * QQ:1406981715
     * 创建日期:2017-03-03
     */
    public class HPythonHelper
    {
        /// <summary>
        /// 执行Python代码(传递0个或1个参数)
        /// </summary>
        /// <param name="value">Python代码或者Python代码文件名</param>
        /// <param name="pKey">参数名,为null表示无参数</param>
        /// <param name="pVal">参数值</param>
        /// <param name="searchPaths">搜索路径列表(引用第三方库时需要加入相应的路径)</param>
        /// <param name="IsFileName">IsFileName=true,则value为Python代码文件名,否则为Python代码</param>
        /// <returns></returns>
        public static object RunCode(string value,string pKey=null,string pVal=null,
            List<string> searchPaths=null,bool IsFileName=true)
        {
            Dictionary<string,object> parameters = null;
            if (!string.IsNullOrEmpty(pKey))
            {
                parameters = new Dictionary<string, object>();
                parameters[pKey] = pVal;
            }
            return RunCode(value, parameters, searchPaths, IsFileName);
        }
        /// <summary>
        /// 执行Python代码
        /// </summary>
        /// <param name="value">Python代码或者Python代码文件名</param>
        /// <param name="parameters">参数,键表示参数名,为null表示无参数</param>
        /// <param name="searchPaths">搜索路径列表(引用第三方库时需要加入相应的路径)</param>
        /// <param name="IsFileName">IsFileName=true,则value为Python代码文件名,否则为Python代码</param>
        /// <returns></returns>
        public static object RunCode(string value, Dictionary<string, object> parameters, 
            List<string> searchPaths = null, bool IsFileName = true)
        {
            ScriptEngine engine = null;
            try
            {
                engine = Python.CreateEngine();
                if (searchPaths != null && searchPaths.Count > 0)
                {
                    ICollection<string> paths = engine.GetSearchPaths();
                    foreach (string item in searchPaths)
                    {
                        paths.Add(item);
                    }
                    engine.SetSearchPaths(paths);
                }
                ScriptScope scope = engine.CreateScope();
                if (parameters != null && parameters.Count > 0)
                {
                    foreach (KeyValuePair<string,object> kvp in parameters)
                    {
                        scope.SetVariable(kvp.Key,kvp.Value);
                    }
                }
                ScriptSource source = IsFileName ? engine.CreateScriptSourceFromFile(value)
                    : engine.CreateScriptSourceFromString(value);
                return source.Execute(scope);
            }
            catch (Exception ex)
            {
                if (engine != null)
                {
                    ExceptionOperations exop = engine.GetService<ExceptionOperations>();
                    throw new Exception(string.Format("Error:{0}", exop.FormatException(ex)));
                }
                else
                {
                    throw;
                }
            }
        }
        /// <summary>
        /// 获取Python中指定的函数名的句柄
        /// </summary>
        /// <typeparam name="T">函数类型</typeparam>
        /// <param name="value">Python代码或者Python代码文件名</param>
        /// <param name="functionName">函数名</param>
        /// <param name="searchPaths">搜索路径列表(引用第三方库时需要加入相应的路径)</param>
        /// <param name="IsFileName">IsFileName=true,则value为Python代码文件名,否则为Python代码</param>
        /// <returns>注:对于无返回值的函数则此处返回null</returns>
        public static T GetFunctionHandle<T>(string value,string functionName, 
            List<string> searchPaths = null, bool IsFileName = true)
        {
            ScriptEngine engine = null;
            try
            {
                engine = Python.CreateEngine();
                if (searchPaths != null && searchPaths.Count > 0)
                {
                    ICollection<string> paths = engine.GetSearchPaths();
                    foreach (string item in searchPaths)
                    {
                        paths.Add(item);
                    }
                    engine.SetSearchPaths(paths);
                }
                //ScriptRuntime runTime = Python.CreateRuntime();
                ScriptScope scope = engine.CreateScope();
                
                ScriptSource source = IsFileName ? engine.CreateScriptSourceFromFile(value)
                    : engine.CreateScriptSourceFromString(value);
                source.Execute(scope);
                return scope.GetVariable<T>(functionName);
            }
            catch (Exception ex)
            {
                if (engine != null)
                {
                    ExceptionOperations exop = engine.GetService<ExceptionOperations>();
                    throw new Exception(string.Format("Error:{0}", exop.FormatException(ex)));
                }
                else
                {
                    throw;
                }
            }
        }
        /// <summary>
        /// 执行指定的函数
        /// </summary>
        /// <param name="value">Python代码或者Python代码文件名</param>
        /// <param name="functionName">函数名</param>
        /// <param name="parameters">函数参数,必须按照函数形参定义顺序列出参数值</param>
        /// <param name="searchPaths">搜索路径列表(引用第三方库时需要加入相应的路径)</param>
        /// <param name="IsFileName">IsFileName=true,则value为Python代码文件名,否则为Python代码</param>
        /// <returns>注:对于无返回值的函数则此处返回null</returns>
        public static object RunFunction(string value,string functionName,List<object> parameters=null, 
            List<string> searchPaths = null, bool IsFileName = true)
        {
            if (parameters == null || parameters.Count == 0)
            {
                var fun = GetFunctionHandle<Func<object>>(value, functionName, searchPaths, IsFileName);
                return fun();
            }
            else if (parameters.Count ==1 )
            {
                var fun = GetFunctionHandle<Func<object, object>>(value, functionName, searchPaths, IsFileName);
                return fun(parameters[0]);
            }
            else if (parameters.Count == 2)
            {
                var fun = GetFunctionHandle<Func<object, object, object>>(value, functionName, 
                    searchPaths, IsFileName);
                return fun(parameters[0], parameters[1]);
            }
            else if (parameters.Count == 3)
            {
                var fun = GetFunctionHandle<Func<object, object, object, object>>(value, functionName, 
                    searchPaths, IsFileName);
                return fun(parameters[0], parameters[1], parameters[2]);
            }
            else if (parameters.Count == 4)
            {
                var fun = GetFunctionHandle<Func<object, object, object, object, object>>(value, functionName, 
                    searchPaths, IsFileName);
                return fun(parameters[0], parameters[1], parameters[2], parameters[3]);
            }
            else if (parameters.Count == 5)
            {
                var fun = GetFunctionHandle<Func<object, object, object, object, object, object>>(value, functionName, 
                    searchPaths, IsFileName);
                return fun(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4]);
            }
            else
            {
                throw new ArgumentException("参数个数不可超过5个!");
            }
        }
    }

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

数据之道

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值