当前位置: 首页 > news >正文

一个在C#中集成Python的例子

一个在C#中集成Python的例子。在C#中可以执行Python脚本,在Python中也可以调用C#宿主中的功能(clr.AddReference('Business'))。 

文件说明

Debug为执行目录

Mgr.exe为执行文件

Py\init.py为python初始化脚本

Py\Lib.zip为python需要的模块,可以在init.py中import

Data为数据库目录

mgr.db为mgr.exe使用的数据库

操作说明

系统设置

可以在这里修改运行的参数

打开一个账户

用户的规则设置

交易

代码说明

Python的说明

在Python中可以调用C#宿主中的功能(clr.AddReference('Business'))。 

import clr
import io
import os
import stringclr.AddReference('System')
clr.AddReference('System.Data')
clr.AddReference('Business')from System import *
from System.Data import *
from Business import *def get_account_money_by_dt(account_id,date):db=Pub.db_name_mgrInitMoney=Pub.select_str(db,"select InitMoney from account where account_id="+account_id)cash=Pub.select_str(db,"select sum(amount_real) from tran where account_id="+account_id+" and tran_date<="+date)stock_amount=float.Parse("0")table_stock=Pub.select(db,"select code_type,code,sum(tran_count_real) as c from tran where account_id="+account_id+" and code<>'' and tran_date<="+date +" group by code_type,code")for dr in table_stock.Rows:code_type=DBUtils.get_str(dr, "code_type");code=DBUtils.get_str(dr, "code");count=DBUtils.get_str(dr, "c");price=Pub.select_str(code_type+"\\"+code,"select close from data_day where dt<="+date+" order by dt desc limit 1")if price<>'':stock_amount=stock_amount+float.Parse(price)*float.Parse(count)if cash=="":cash="0"if InitMoney=="":InitMoney="0"return (float.Parse(InitMoney)+float.Parse(cash)+stock_amount).ToString("0.00")

C#的说明

加载Python环境

            instance = new Py();
            instance.init_py_lib();

        public void init_py_lib(){engine = IronPython.Hosting.Python.CreateEngine();scope = engine.CreateScope();engine.Runtime.IO.SetOutput(Output,Encoding.Unicode);engine.SetTrace(on_trace);StringBuilder sb = new StringBuilder();sb.AppendLine(@"import sys ");sb.AppendLine(@"sys.path.append("".\py\Lib.zip"") ");sb.AppendLine(@"sys.path.append("".\scripts"") ");ScriptSource source = engine.CreateScriptSourceFromString(sb.ToString());source.Execute(scope);string init_py = Pub.exe_dir + @"\py\init.py";if (System.IO.File.Exists(init_py)){ScriptSource source_init = engine.CreateScriptSourceFromFile(init_py);source_init.Execute(scope);}}

执行脚本

 

       public Boolean Execute(string script, out string msg, out IronPyErrors err, ExecRequest request){msg = "";err = new IronPyErrors();StringBuilder sb = request.log;sb.AppendLine("开始 "+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") );sb.AppendLine("------");try{last_trace_lineno = "";last_trace_result = "";ScriptSource source = engine.CreateScriptSourceFromString(script);                CompiledCode cc = source.Compile(err);  if (err.Items.Count > 0){err.ToStringBuilder(sb);msg = "编译错误";sb.Append(msg);return false;}scope.SetVariable("request", request);Py.instance.Output.SetLength(0);string sql_err = DataAccess.DataConn.clear_err();cc.Execute(scope);               Py.instance.Output.Flush();string print_s = Encoding.Unicode.GetString(Py.instance.Output.ToArray());sql_err = DataAccess.DataConn.clear_err();if (sql_err != "")sb.AppendLine(sql_err);sb.AppendLine(print_s);sb.AppendLine("------");msg = "运行完成 "+ DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") ;sb.Append(msg);return true;}catch (Exception e){if (last_trace_lineno != "")msg = "trace line:" + last_trace_lineno;if (last_trace_result != "")msg = msg + " " + "trace:" + last_trace_result;msg = msg + " " + e.Message;sb.Append(msg);}return false;}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
using IronPython;
using IronPython.Runtime;
using IronPython.Modules;
using IronPython.Compiler;
using IronPython.Runtime.Exceptions;
using IronPython.Hosting;
using Business;namespace Mgr
{public class Py{public static Py instance = null;public static void init(){if (instance != null)return;instance = new Py();instance.init_py_lib();}public ScriptEngine engine = null;public ScriptScope scope = null;public static string get_key(string name){return name.Trim().ToLower();}public static Dictionary<string , ScriptSource> ScriptDict = new Dictionary<string , ScriptSource>();public string set_script(string id ,string script){if (id == "")id = Guid.NewGuid().ToString();id = get_key(id);ScriptSource source = engine.CreateScriptSourceFromString(script);ScriptDict[id] = source;return id;}public string last_trace_lineno = "";public string last_trace_result = "";public TracebackDelegate on_trace(TraceBackFrame frame, string result, object payload){last_trace_lineno = frame.f_lineno.ToString();last_trace_result = result;return on_trace;}public Boolean Compile(string script,out string msg, out CompiledCode cc, out  IronPyErrors err){msg = "";err = new IronPyErrors();cc = null;try{ScriptSource source = engine.CreateScriptSourceFromString(script);              cc = source.Compile(err);msg = "编译完成";return true;}catch (Exception e){msg = e.Message;}return false;}public Boolean Execute_cc(CompiledCode cc, out string msg, ExecRequest request){msg = "";StringBuilder sb = request.log;sb.AppendLine("开始 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));sb.AppendLine("------");try{last_trace_lineno = "";last_trace_result = "";scope.SetVariable("request", request);Py.instance.Output.SetLength(0);string sql_err = DataAccess.DataConn.clear_err();cc.Execute(scope);Py.instance.Output.Flush();string print_s = Encoding.Unicode.GetString(Py.instance.Output.ToArray());sql_err = DataAccess.DataConn.clear_err();if (sql_err != "")sb.AppendLine(sql_err);sb.AppendLine(print_s);sb.AppendLine("------");msg = "运行完成 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");sb.Append(msg);return true;}catch (Exception e){if (last_trace_lineno != "")msg = "trace line:" + last_trace_lineno;if (last_trace_result != "")msg = msg + " " + "trace:" + last_trace_result;msg = msg + " " + e.Message;sb.Append(msg);}return false;}public Boolean Execute(string script, out string msg, out IronPyErrors err, ExecRequest request){msg = "";err = new IronPyErrors();StringBuilder sb = request.log;sb.AppendLine("开始 "+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") );sb.AppendLine("------");try{last_trace_lineno = "";last_trace_result = "";ScriptSource source = engine.CreateScriptSourceFromString(script);                CompiledCode cc = source.Compile(err);  if (err.Items.Count > 0){err.ToStringBuilder(sb);msg = "编译错误";sb.Append(msg);return false;}scope.SetVariable("request", request);Py.instance.Output.SetLength(0);string sql_err = DataAccess.DataConn.clear_err();cc.Execute(scope);               Py.instance.Output.Flush();string print_s = Encoding.Unicode.GetString(Py.instance.Output.ToArray());sql_err = DataAccess.DataConn.clear_err();if (sql_err != "")sb.AppendLine(sql_err);sb.AppendLine(print_s);sb.AppendLine("------");msg = "运行完成 "+ DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") ;sb.Append(msg);return true;}catch (Exception e){if (last_trace_lineno != "")msg = "trace line:" + last_trace_lineno;if (last_trace_result != "")msg = msg + " " + "trace:" + last_trace_result;msg = msg + " " + e.Message;sb.Append(msg);}return false;}public MemoryStream Output = new MemoryStream();public void init_py_lib(){engine = IronPython.Hosting.Python.CreateEngine();scope = engine.CreateScope();engine.Runtime.IO.SetOutput(Output,Encoding.Unicode);engine.SetTrace(on_trace);StringBuilder sb = new StringBuilder();sb.AppendLine(@"import sys ");sb.AppendLine(@"sys.path.append("".\py\Lib.zip"") ");sb.AppendLine(@"sys.path.append("".\scripts"") ");ScriptSource source = engine.CreateScriptSourceFromString(sb.ToString());source.Execute(scope);string init_py = Pub.exe_dir + @"\py\init.py";if (System.IO.File.Exists(init_py)){ScriptSource source_init = engine.CreateScriptSourceFromFile(init_py);source_init.Execute(scope);}}}public class IronPyErrorsItem{public string Message { get; set; }public int ErrorCode { get; set; }public Severity sev { get; set; }public SourceSpan Span { get; set; }public string get_info(){string line = "";line = Span.Start.Line.ToString() + "行" + Span.Start.Column.ToString() + "列";line = line + "(" + sev.ToString() +" " + ErrorCode.ToString()+"): ";line = line +  Message;return line;}}public class IronPyErrors : ErrorListener{public List<IronPyErrorsItem> Items = new List<IronPyErrorsItem>();public void ToStringBuilder(StringBuilder sb){foreach (IronPyErrorsItem i in Items){sb.AppendLine(i.get_info());}}public override void ErrorReported(ScriptSource source, string message, Microsoft.Scripting.SourceSpan span, int errorCode, Microsoft.Scripting.Severity severity){IronPyErrorsItem i = new IronPyErrorsItem{Message = message,ErrorCode = errorCode,sev = severity,Span = span};Items.Add(i);}
}
}

相关文章:

一个在C#中集成Python的例子

一个在C#中集成Python的例子。在C#中可以执行Python脚本&#xff0c;在Python中也可以调用C#宿主中的功能&#xff08;clr.AddReference(Business)&#xff09;。 文件说明 Debug为执行目录 Mgr.exe为执行文件 Py\init.py为python初始化脚本 Py\Lib.zip为python需要的模块&…...

基于RandLA-Net深度学习模型的激光点云语义分割

一、场景要素语义分割部分的文献阅读笔记 RandLA-Net是一种高效、轻量级的神经网络&#xff0c;其可直接逐点推理大规模点云的语义标签。RandLA-Net基于随机点采样获得了显著的计算和内存效率&#xff0c;并采用新的局部特征聚合模块有效地保留了几何细节&#xff0c;弥补了随机…...

C语言的结构体与联合体

引言 C语言提供了结构体和联合体两种聚合数据类型&#xff0c;使得程序员可以创建包括多个数据类型的复杂数据结构。结构体用于将不同类型的数据组合成一个单元&#xff0c;而联合体用于在同一存储空间中存储不同类型的数据。本篇文章将详细介绍C语言中的结构体和联合体&#x…...

React Hooks小记(三)_forwardRef

forwardRef 【写在前面】 ​ 1、ref 的作用是获取实例&#xff0c;但由于函数组件不存在实例&#xff0c;因此无法通过 ref 获取函数组件的实例引用&#xff0c;而 React.forwardRef 就是用来解决这个问题的。 ​ 2、React.forwardRef 会创建一个 React 组件&#xff0c;这个组…...

面试复习记录

六级终于结束了&#xff0c;之前背的八股几乎也忘得差不多了&#xff0c;今天开始继续准备秋招&#xff0c;以下是每天的安排&#xff0c;会按时更新&#xff0c;就当是一种对自己的督促&#xff0c;也欢迎小伙伴们一起来互相监督。 2024.6.16 力扣&#xff1a;sql基础题库50…...

块级元素与行内元素详解

在网页设计与开发中&#xff0c;元素根据其在页面布局中的表现可分为两大类&#xff1a;块级元素&#xff08;Block-level Elements&#xff09;和行内元素&#xff08;Inline Elements&#xff09;。理解它们的特性和使用规则对于构建结构清晰、布局合理的网页至关重要。 块级…...

Kotlin编程实践-【Java如何调用Kotlin中带默认值参数的函数】

问题 如果你有一个带有默认参数值的 Kotlin 函数&#xff0c;如何从 Java 调用它而无须为每个参数显式指定值&#xff1f; 方案 为函数添加注解JvmOverloads。 也就是为Java添加重载方法&#xff0c;这样Java调用Kotlin的方法时就不用传递全部的参数了。 示例 在 Kotlin …...

中国城市统计年鉴(1985-2023年)

数据年限&#xff1a;1985-2023 数据格式&#xff1a;pdf、excel 数据内容&#xff1a;共分四个部分 第一部分是全国城市行政区划&#xff0c;列有不同区域、不同级别的城市分布情况&#xff1b; 第二、三部分分别是地级以上城市统计资料和县级城市统计资料&#xff0c;具体包括…...

RestTemplate远程请求的艺术

1 简说 编程是一门艺术,追求优雅的代码就像追求优美的音乐。 很多有多年工作经验的开发者,在使用RestTemplate之前常常使用HttpClient,然而接触了RestTemplate之后,却愿意放弃多年相处的“老朋友”,转向RestTemplate。那么一定是RestTemplate有它的魅力,有它的艺术风范。…...

Spring 整合 MyBatis 底层源码解析

大家好&#xff0c;我是柳岸花开。今天我们要讲的是 Spring 整合 MyBatis 的底层源码解析。希望大家能更深入理解 Spring 和 MyBatis 的整合原理&#xff0c;并应用到实际项目中。 由很多框架都需要和Spring进行整合&#xff0c;而整合的核心思想就是把其他框架所产生的对象放到…...

LeetCode 189.轮转数组

1.这个题我用的方法比较巧妙&#xff0c;大家如果觉得好的话&#xff0c;就给个免费的赞吧^ _ ^,谢谢了。 void reverse(int* nums,int left,int right) {while(left < right){int a nums[left];nums[left] nums[right];nums[right] a;left;right--;} } void rotate(int…...

JDK17 你的下一个白月光

JDK版本升级的非常快&#xff0c;现在已经到JDK20了。JDK版本虽多&#xff0c;但应用最广泛的还得是JDK8&#xff0c;正所谓“他发任他发&#xff0c;我用Java8”。 但实际情况却不是这样&#xff0c;越来越多的java工程师拥抱 JDK17&#xff0c;于是了解了一下 JDK17新语法&a…...

springboot优雅shutdown时如何保障异步线程的安全

我前面写了一篇springboot优雅shutdown的文章&#xff0c;看起来一切很美好。 https://blog.csdn.net/chenshm/article/details/139640775 那是因为没有进行多线程测试。如果一个请求中包括阻塞线程&#xff08;主线程&#xff09;和非阻塞线程&#xff08;异步线程&#xff09…...

C++格式化库fmt使用方法

1. 格式化库fmt简介 fmt github地址 api说明 格式化参数说明 内容的格式化&#xff0c;体现在代码中主要表现为字符串、基本类型、自定义类型的拼接。例如说打印日志、拼接变量等。C中我们会经常使用类似printf,snprintf(C风格使用不方便),std::string.append(繁琐), std::io…...

HTML 颜色名:网页设计的调色板

HTML 颜色名:网页设计的调色板 在网页设计和开发中,颜色是一个关键元素,它不仅影响视觉效果,还能传达情感和品牌信息。HTML 颜色名是用于在 HTML 和 CSS 代码中指定颜色的预定义名称。这些颜色名易于记忆,方便设计师和开发者快速选择和应用颜色。本文将详细介绍 HTML 颜色…...

12306 火车票价格解析 (PHP 解析)

1. 从接口拿数据 日期 出发站 终点站 都填上 xxx/otn/leftTicketPrice/queryAllPublicPrice?leftTicketDTO.train_date2024-06-15&leftTicketDTO.from_stationBJP&leftTicketDTO.to_stationSJP&purpose_codesADULT 返回的数据是这样的 {"validateMess…...

了解统计学中不同类型的分布

目录 一、说明 二、均匀分布&#xff1a; 三、机器学习和数据科学中的均匀分布示例&#xff1a; 3.1 对数正态分布&#xff1a; 3.2 机器学习和数据科学中的对数正态分布示例&#xff1a; 四、 帕累托分布 4.1 什么是幂律&#xff1f; 4.2 机器学习和数据科学中的帕累托分布示例…...

k8s-CCE创建工作负载变量引用

CCE创建工作负载变量引用 背景&#xff0c;看到cce创建负载时会生成变量&#xff0c;如下。在skywaking-agent的使用&#xff0c;想要调用cce负载变量生成service_name。 -Dskywalking.agent.authentication里含有敏感信息需要写到配置项。简单粗糙的都写到配置项好像不合适。…...

后端主流框架--Spring02

前言:上篇关于Spring的文章介绍了一些Spring的基本知识&#xff0c;此篇文章主要分享一下如何配置Spring环境&#xff0c;如何注入等。 Spring项目构建 导入Spring相关JAR包 <dependency><groupId>org.springframework</groupId><artifactId>spring…...

[数据集][目标检测]减速带检测数据集VOC+YOLO格式5400张1类别

数据集格式&#xff1a;Pascal VOC格式YOLO格式(不包含分割路径的txt文件&#xff0c;仅仅包含jpg图片以及对应的VOC格式xml文件和yolo格式txt文件) 图片数量(jpg文件个数)&#xff1a;5400 标注数量(xml文件个数)&#xff1a;5400 标注数量(txt文件个数)&#xff1a;5400 标注…...

[2025CVPR]DeepVideo-R1:基于难度感知回归GRPO的视频强化微调框架详解

突破视频大语言模型推理瓶颈,在多个视频基准上实现SOTA性能 一、核心问题与创新亮点 1.1 GRPO在视频任务中的两大挑战 ​安全措施依赖问题​ GRPO使用min和clip函数限制策略更新幅度,导致: 梯度抑制:当新旧策略差异过大时梯度消失收敛困难:策略无法充分优化# 传统GRPO的梯…...

Debian系统简介

目录 Debian系统介绍 Debian版本介绍 Debian软件源介绍 软件包管理工具dpkg dpkg核心指令详解 安装软件包 卸载软件包 查询软件包状态 验证软件包完整性 手动处理依赖关系 dpkg vs apt Debian系统介绍 Debian 和 Ubuntu 都是基于 Debian内核 的 Linux 发行版&#xff…...

【位运算】消失的两个数字(hard)

消失的两个数字&#xff08;hard&#xff09; 题⽬描述&#xff1a;解法&#xff08;位运算&#xff09;&#xff1a;Java 算法代码&#xff1a;更简便代码 题⽬链接&#xff1a;⾯试题 17.19. 消失的两个数字 题⽬描述&#xff1a; 给定⼀个数组&#xff0c;包含从 1 到 N 所有…...

MVC 数据库

MVC 数据库 引言 在软件开发领域,Model-View-Controller(MVC)是一种流行的软件架构模式,它将应用程序分为三个核心组件:模型(Model)、视图(View)和控制器(Controller)。这种模式有助于提高代码的可维护性和可扩展性。本文将深入探讨MVC架构与数据库之间的关系,以…...

VTK如何让部分单位不可见

最近遇到一个需求&#xff0c;需要让一个vtkDataSet中的部分单元不可见&#xff0c;查阅了一些资料大概有以下几种方式 1.通过颜色映射表来进行&#xff0c;是最正规的做法 vtkNew<vtkLookupTable> lut; //值为0不显示&#xff0c;主要是最后一个参数&#xff0c;透明度…...

AI编程--插件对比分析:CodeRider、GitHub Copilot及其他

AI编程插件对比分析&#xff1a;CodeRider、GitHub Copilot及其他 随着人工智能技术的快速发展&#xff0c;AI编程插件已成为提升开发者生产力的重要工具。CodeRider和GitHub Copilot作为市场上的领先者&#xff0c;分别以其独特的特性和生态系统吸引了大量开发者。本文将从功…...

用docker来安装部署freeswitch记录

今天刚才测试一个callcenter的项目&#xff0c;所以尝试安装freeswitch 1、使用轩辕镜像 - 中国开发者首选的专业 Docker 镜像加速服务平台 编辑下面/etc/docker/daemon.json文件为 {"registry-mirrors": ["https://docker.xuanyuan.me"] }同时可以进入轩…...

全志A40i android7.1 调试信息打印串口由uart0改为uart3

一&#xff0c;概述 1. 目的 将调试信息打印串口由uart0改为uart3。 2. 版本信息 Uboot版本&#xff1a;2014.07&#xff1b; Kernel版本&#xff1a;Linux-3.10&#xff1b; 二&#xff0c;Uboot 1. sys_config.fex改动 使能uart3(TX:PH00 RX:PH01)&#xff0c;并让boo…...

基于matlab策略迭代和值迭代法的动态规划

经典的基于策略迭代和值迭代法的动态规划matlab代码&#xff0c;实现机器人的最优运输 Dynamic-Programming-master/Environment.pdf , 104724 Dynamic-Programming-master/README.md , 506 Dynamic-Programming-master/generalizedPolicyIteration.m , 1970 Dynamic-Programm…...

Docker 本地安装 mysql 数据库

Docker: Accelerated Container Application Development 下载对应操作系统版本的 docker &#xff1b;并安装。 基础操作不再赘述。 打开 macOS 终端&#xff0c;开始 docker 安装mysql之旅 第一步 docker search mysql 》〉docker search mysql NAME DE…...