# PPTxPython **Repository Path**: ahddredlover/pptx-python ## Basic Information - **Project Name**: PPTxPython - **Description**: 基于VBA简单实现PPT嵌入运行Python程序 - 可满足Python教学工作者的日常基础Python课程教学,即在放映PowerPoint时可以直接运行Python代码并显示代码运行结果,使课程教学过程更加高效、便捷!已支持中文 UTF-8编码 - **Primary Language**: Visual Basic - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 2 - **Created**: 2021-11-01 - **Last Updated**: 2024-06-08 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ## 基于VBA简单实现PPT嵌入运行Python程序 #### :tw-1f3a6: 效果图 ![运行截图](https://images.gitee.com/uploads/images/2021/0714/172347_cbed3d86_1794083.png "微信截图_20210714172337.png") #### :tw-1f4a1: 实现思路 ![实现思路](https://images.gitee.com/uploads/images/2021/0715/125247_fe5ea746_1794083.png "PPT嵌入运行Python思路.png") #### :tw-1f4bb: 运行环境 1. MS Office PowerPoint (未禁用VBA) 2. 已部署所需的Python运行环境 #### :tw-2705: 功能预想 可满足Python教学工作者的日常基础Python课程教学,即在放映PowerPoint时可以直接运行Python代码并显示代码运行结果,使课程教学过程更加高效、便捷!已支持中文`utf-8`编码 #### :tw-23-20e3: 代码实现 ##### :tw-25aa: 单击“运行Python代码”按钮 ``` Private Sub CommandButton1_Click() '写入代码 Dim f, txt, result As String f = "run.py" Open f For Output As #1 Print #1, TextBox_in.Value Close #1 '中文编码问题,需将文件转为utf-8编码格式 Dim fileName As String fileName = "run.py" Call ConvFile(fileName, fileName) '运行Python文件并重定向结果 Dim res As Long res = Shell("cmd.exe /C python " & "run.py > res.txt", vbHide) '延时处理 Dim Savetime As Single CommandButton1.Caption = "运行中..." Savetime = Timer '记下开始的时间 While Timer < Savetime + 1 '循环等待 DoEvents '转让控制权,以便让操作系统处理其它的事件 Wend CommandButton1.Caption = "运行Python代码" '读取结果 Open "res.txt" For Input As #1 Do While Not EOF(1) Line Input #1, txt result = result & txt & vbCr Loop Close #1 TextBox_out.Text = result End Sub ``` ##### :tw-25aa: 转换文件编码为“utf-8”,解决中文编码问题 ``` Private Sub ConvFile(InputFile As String, OutputFile As String) Dim ReadStream As Object Set ReadStream = CreateObject("ADODB.Stream") Dim FileContent As String With ReadStream .Type = 2 'adTypeText '.Charset = "UNICODE" .Charset = "GB2312" ' ANSI '.Charset = "UTF-8" .Open .LoadFromFile InputFile FileContent = .ReadText .Close End With Set ReadStream = Nothing Dim WriteStream As Object Set WriteStream = CreateObject("ADODB.Stream") With WriteStream .Type = 2 'adTypeText .Charset = "UTF-8" .Open .WriteText FileContent .SaveToFile OutputFile, 2 'adSaveCreateOverWrite .Flush .Close End With Set WriteStream = Nothing End Sub ``` #### :tw-274e: 现存缺陷 由于个人能力有限,目前仅支持对于简单基础的Python代码的嵌入式运行,无法满足带有输入的代码(如`input()`等)以及一些调用复杂库的代码输出。只能满足日常基础Python课程的需要 #### :tw-1f4dd: 关于作者: 学生 计算机科学与技术本科在读 前端初学者 ![WeChat](https://images.gitee.com/uploads/images/2021/0714/170442_c95133c1_1794083.png "微信")![赞赏](https://images.gitee.com/uploads/images/2021/0714/170750_0ede35e5_1794083.png "赞赏") 微信公众号:浙江技术救命稻草 ![喜欢请记得关注哦](https://images.gitee.com/uploads/images/2021/0714/170842_c32d288f_1794083.png "喜欢请记得关注哦")