一个在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 string

clr.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_mgr
  InitMoney=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);
        }
}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/713381.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

大数据实训项目(小麦种子)-02、实训项目整体功能介绍与演示

文章目录 前言界面及功能描述实现功能描述技术选型界面展示首页界面功能1&#xff1a;HDFS&#xff0c;选择文件上传文件详细步骤 功能2&#xff1a;MapReduce预处理数据功能3&#xff1a;Hbase存储小麦种子数据并查询前10条记录功能4&#xff1a;Hive分析原始csv文件数据并ech…

【GO-OpenCV】go-cv快速配置

最近对golang实现目标检测心血来潮&#xff0c;尝试在没有sudo权限的平台配置go-cv,有所发现&#xff0c;索性多个平台都做尝试 安装Go语言&#xff08;Golang&#xff09; 通过包管理器安装&#xff08;适用于Debian/Ubuntu&#xff09;(有点慢) 更新包列表&#xff1a; sud…

简单的基于小波变换的图像压缩(Python)

2023 沃尔夫数学奖得主&#xff0c;给了杜克大学的Ingrid Daubechies&#xff08;多贝西&#xff09;教授 以色列沃尔夫基金会理事会成员 Michael Lin 教授在周二宣布: “Ingrid Daubechies is awarded the Wolf Prize for her work in the creation and development of wavel…

搭建k8s集群报错unknown command “\u00a0“ for “kubeadm init“

搭建k8s报错unknown command “\u00a0” for “kubeadm init” 网上搜了一下&#xff0c;是因为复制过来的命令前面包含了空格&#xff0c;将复制的命令放到idea可以清楚看到几个命令前面有空格&#xff0c;删除掉就好了&#xff0c;记录一下

设计模式-享元模式Flyweight(结构型)

享元模式(Flyweight) 享元模式是一种结构型模式&#xff0c;它主要用于减少创建对象的数量&#xff0c;减少内存占用。通过重用现有对象的方式&#xff0c;如果未找到匹配对象则新建对象。线程池、数据库连接池、常量池等池化的思想就是享元模式的一种应用。 图解 角色 享元工…

【团队成长】2024-24周周报-第一次组会人员分工48期推文预告

大家好&#xff01;我们是IndustryOR 团队&#xff0c;致力于分享业界落地的算法技术。欢迎关注微信公众号/知乎/CSDN【运筹匠心】 。 记录人&#xff1a;张哲铭&#xff0c;算法专家&#xff0c;某互联网大厂 【团队成长/个人成长】系列的推文会以 【工作周报】 的方式记录Ind…

【机器学习】人工智能与气候变化:利用深度学习与机器学习算法预测和缓解环境影响

&#x1f4dd;个人主页&#xff1a;哈__ 期待您的关注 目录 &#x1f525;引言 1.1 背景介绍 1.2 人工智能与机器学习的崛起 1.3 本文内容概述 &#x1f528;气候变化的挑战 2.1 现今气候变化带来的影响和挑战 2.2 引发关注的气候变化趋势和数据 &#x1f916;人工智能…

使用SpringBoot对接Kafka

Kafka是什么&#xff0c;以及如何使用SpringBoot对接Kafka 一、Kafka与流处理 我们先来看看比较正式的介绍&#xff1a;Kafka是一种流处理平台&#xff0c;由LinkedIn公司创建&#xff0c;现在是Apache下的开源项目。Kafka通过发布/订阅机制实现消息的异步传输和处理。它具有高…

VMware Workstation安装及使用详细教程

如何安装VMware Workstation的详细教程 一、准备工作 1. 下载VMware Workstation&#xff1a; 访问VMware官方网站&#xff0c;找到VMware Workstation的下载页面。根据您的操作系统&#xff08;Windows或macOS&#xff09;选择相应的版本进行下载。确保您的计算机满足VMwar…

牛客小白月赛96 解题报告 | 珂学家

前言 题解 A. 最少胜利题数 签到 n1 len(set(input())) n2 len(set(input()))if n1 < n2:n1, n2 n2, n1print (-1 if n1 6 else n1 - n2 1)B. 最少操作次数 思路: 分类讨论 只有-1,0,1,2这四种结果 特判 01, 10 n int(input()) s input()# 枚举 from collectio…

vue之一键部署的shell脚本和它的点.bat文件、海螺AI、ChatGPT

MENU 前言vite.config.ts的配置deploy文件夹的其他内容remote.shpwd.txtdeploy.bat 前言 1、在src同级新建deploy.bat文件&#xff1b; 2、在src同级新建deploy文件夹&#xff0c;文件夹中新建pwd.txt和remote.sh文件&#xff1b; 3、配置好后&#xff0c;直接双击deploy.bat文…

Java_FileIO流

存储数据的方案 有些数据想长久保存起来&#xff0c;咋整&#xff1f; 文件时非常重要的存储方式&#xff0c;在计算机硬盘中。 即便断电&#xff0c;或者程序终止了&#xff0c;存储在硬盘文件中的数据也不会丢失。 File File 是Java.io.包下的类&#xff0c;File类对象&…

C++ string字符串的使用和简单模拟实现

目录 前言 1. string简介 2. string的使用和简单模拟实现 2.1 string类的定义 2.2 string(),~string()和c_str() 2.2 size&#xff0c;重载符号[ ]&#xff0c;begin和end函数 2.3 push_back&#xff0c;reserve&#xff0c;append&#xff0c;运算符重载 2.4 insert和…

DDPM公式推导(三)

2 Background 扩散模型【53】是一种以 p θ ( x 0 ) : ∫ p θ ( x 0 : T ) d x 1 : T p_\theta\left(\mathbf{x}_0\right):\int p_\theta\left(\mathbf{x}_{0: T}\right) d \mathbf{x}_{1: T} pθ​(x0​):∫pθ​(x0:T​)dx1:T​ 形式的潜在变量模型&#xff0c;其中 x 1…

机器真的能思考、学习和智能地行动吗?

In this post, were going to define what machine learning is and how computers think and learn. Were also going to look at some history relevant to the development of the intelligent machine. 在这篇文章中&#xff0c;我们将定义机器学习是什么&#xff0c;以及…

BerkeleyDB练习

代码; #include <db.h> #include <stdio.h>int main() {DB *dbp;db_create(&dbp, NULL, 0);printf("Berkeley DB version: %s\n", db_version(NULL, NULL, NULL));dbp->close(dbp, 0);return 0; } 编译运行

Android studio在Ubuntu桌面上 创建桌面图标,以及导航栏图标

Android studio在Ubuntu桌面上 创建桌面图标&#xff0c;以及导航栏图标 1. 下载Android studio for Lunux 免安装版本之后&#xff0c;解压 2. 通过控制台运行 ~/Documents/android-studio-2024.1.1.2-linux/android-studio/bin$ ./studio.sh 3. 选择菜单&#xff0c;Tools…

1586. 扫地机器人

问题描述 Mike同学在为扫地机器人设计一个在矩形区域中行走的算法,Mike是这样设计的:先把机器人放在出发点 (1,1)(1,1) 点上,机器人在每个点上都会沿用如下的规则来判断下一个该去的点是哪里。规则:优先向右,如果向右不能走(比如:右侧出了矩形或者右侧扫过了)则尝试向…

基于51单片机的烟雾报警器设计-ADC0809

一.硬件方案 火灾报警器采用51单片机为核心控制器&#xff0c;利用气体传感器MQ-2、ADC0809模数转换器、DS18B20温度传感器等实现基本功能。通过这些传感器和芯片&#xff0c;当环境中可燃气体浓度或温度等发生变化时系统会发出相应的灯光报警信号和声音报警信号&#xff0c;以…

28.启动与暂停程序

上一个内容&#xff1a;27.设计注入功能界面 以它 27.设计注入功能界面 的代码为基础进行修改 点击添加游戏按钮之后就把游戏启动了 CWndINJ.cpp文件中修改&#xff1a; void CWndINJ::OnBnClickedButton1() {// TODO: 在此添加控件通知处理程序代码/*ExeLst.InsertItem(0, L…