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

golang调用python3,并使用python模块中的方法

因项目需要,很多代码和python模块是go语言没有的,虽然有个项目是转化python代码到golang代码,但是还没开始用,关键是python引用的模块如此之多,不可能都去转换对吧。

py3安装方法

*************************************

https://github.com/DataDog/go-python3/issues/24

1.先安装chocolatey

Windows PowerShell

版权所有 (C) Microsoft Corporation。保留所有权利。

尝试新的跨平台 PowerShell https://aka.ms/pscore6 PS C:\Users\Administrator>Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))Forcing web requests to allow TLS v1.2 (Required for requests to Chocolatey.org)

Getting latest version of the Chocolatey package for download.

Not using proxy.

Getting Chocolatey from https://community.chocolatey.org/api/v2/package/chocolatey/0.11.3.

Downloading https://community.chocolatey.org/api/v2/package/chocolatey/0.11.3 to C:\Users\Administrator\AppData\Local\Temp\chocolatey\chocoInstall\chocolatey.zip

Not using proxy.

Extracting C:\Users\Administrator\AppData\Local\Temp\chocolatey\chocoInstall\chocolatey.zip to C:\Users\Administrator\AppData\Local\Temp\chocolatey\chocoInstall

Installing Chocolatey on the local machine

Creating ChocolateyInstall as an environment variable (targeting 'Machine')

Setting ChocolateyInstall to 'C:\ProgramData\chocolatey'

WARNING: It's very likely you will need to close and reopen your shell

before you can use choco.

Restricting write permissions to Administrators

We are setting up the Chocolatey package repository.

The packages themselves go to 'C:\ProgramData\chocolatey\lib'

(i.e. C:\ProgramData\chocolatey\lib\yourPackageName).

A shim file for the command line goes to 'C:\ProgramData\chocolatey\bin'

and points to an executable in 'C:\ProgramData\chocolatey\lib\yourPackageName'.

Creating Chocolatey folders if they do not already exist.

WARNING: You can safely ignore errors related to missing log files when

upgrading from a version of Chocolatey less than 0.9.9.

'Batch file could not be found' is also safe to ignore.

'The system cannot find the file specified' - also safe.

chocolatey.nupkg file not installed in lib.

Attempting to locate it from bootstrapper.

PATH environment variable does not have C:\ProgramData\chocolatey\bin in it. Adding...

警告: Not setting tab completion: Profile file does not exist at

'C:\Users\Administrator\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1'.

Chocolatey (choco.exe) is now ready.

You can call choco from anywhere, command line or powershell by typing choco.

Run choco /? for a list of functions.

You may need to shut down and restart powershell and/or consoles

first prior to using choco.

Ensuring Chocolatey commands are on the path

Ensuring chocolatey.nupkg is in the lib folder

PS C:\Users\Administrator> choco -v

0.11.3

PS C:\Users\Administrator>choco upgrade chocolatey

Chocolatey v0.11.3

Upgrading the following packages:

chocolatey

By upgrading, you accept licenses for the packages.

chocolatey v0.11.3 is the latest version available based on your source(s).

Chocolatey upgraded 0/1 packages.

See the log for details (C:\ProgramData\chocolatey\logs\chocolatey.log).

Did you know the proceeds of Pro (and some proceeds from other

licensed editions) go into bettering the community infrastructure?

Your support ensures an active community, keeps Chocolatey tip-top,

plus it nets you some awesome features!

https://chocolatey.org/compare

PS C:\Users\Administrator>

2.下载https://github.com/christian-korneck/snack

3.执行build.bat文件,自动安装python和设置pkg-config

4.修改go.mod中的go 1.17版本为你当前安装的版本号,比如go 1.16

5.然后go mod tidy更新mod文件

6.进入文件夹内执行go run main.go编译生成exe文件,将C:\dist\python37.dll拷贝到exe文件所在文件夹内才能运行

7.刚才那个bat文件没有安装pip,所以要在PowerShell里安装pip

$curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py#下载安装脚本

$ sudo pythonget-pip.py#运行安装脚本

注意:用哪个版本的Python运行安装脚本,pip就被关联到哪个版本,如果是Python3则执行以下命令:

$ sudo python3get-pip.py#运行安装脚本。

Win下:pythonget-pip.py

PS C:\Users\Administrator> pip -V

pip 21.3.1 from c:\py\lib\site-packages\pip (python 3.7)

8.开始安装依赖包:设置国内代理,否则超级慢

pip install-i https://pypi.tuna.tsinghua.edu.cn/simpleansys-mapdl-reader

PS C:\Users\Administrator>pip install -i https://pypi.tuna.tsinghua.edu.cn/simple ansys-mapdl-reader

Collecting ansys-mapdl-reader

Using cached ansys_mapdl_reader-0.51.7-cp37-cp37m-win_amd64.whl (1.1 MB)

Collecting matplotlib>=3.0.0

Using cached matplotlib-3.5.1-cp37-cp37m-win_amd64.whl (7.2 MB)

Collecting tqdm>=4.45.0

Using cached tqdm-4.62.3-py2.py3-none-any.whl (76 kB)

Collecting appdirs>=1.4.0

Using cached appdirs-1.4.4-py2.py3-none-any.whl (9.6 kB)

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pyvista

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple ansys-mapdl-core

pip install-i https://pypi.tuna.tsinghua.edu.cn/simpleansys-dpf-post

pip install-i https://pypi.tuna.tsinghua.edu.cn/simpleansys-dpf-core

9.go-py3例子

Golang中调用Python3 - 知乎

调用python模块中的方法

比如,一个python的代码如下

# plot.py import os,sys import ansys.mapdl.reader as aaa #import pyvista as pv # from ansys.mapdl import reader as pymapdl_reader # from ansys.mapdl.reader import examples # import ansys.mapdl # import ansys.mapdl.reader #import pyansys #dir_path = os.path.dirname(os.path.realpath(__file__)) #目录路径 #print(dir_path) #rstfile = os.path.join(dir_path, '1641543541831483300_0.rst') #本地rst文件 ########网上例子################################################################ # def read_ansys(): # dir_path = os.path.dirname(os.path.realpath(__file__)) #目录路径 # print(dir_path) # rstfile = os.path.join(dir_path, '2.rst') #本地rst文件 # rstfile = examples.rstfile #网上例子 # result = aaa.read_binary('2.rst') #新版读文件 # freqs = result.time_values # print(freqs) # nnum, disp = result.nodal_solution(0) # print(disp) # cpos = result.plot_nodal_solution(0) #显示到窗口 # vtkfile = os.path.join('', 'hexrst1.vtk') # result.save_as_vtk('hexrst1.vtk') ############################################################################### # if __name__ == '__main__': # sys.exit(read_ansys())

在python中,上述代码用aaa包中的read_binary方法来读取一个文件夹里的文件对吧。到go里怎么做呢?

package main import ( "fmt" "github.com/DataDog/go-python3" "log" "os" ) func init() { // 1. 初始化python环境 python3.Py_Initialize() if !python3.Py_IsInitialized() { fmt.Println("Error initializing the python interpreter") os.Exit(1) } } func main() { // 2. 设置本地python import 的路径 // p := "C:/py/Lib/site-packages" // InsertBeforeSysPath(p) // 3. 导入hello模块 plot := ImportModule("D:/snack/ansys", "plot") //导入python代码plot.py qin := plot.GetAttrString("aaa") //获取函数-plot.py里的导入包import ansys.mapdl.reader as aaa log.Print(qin) sep := python3.PyUnicode_FromString("2.rst") //必须是ansys14+生成的rst文件!! res2 := qin.CallMethodArgs("read_binary", sep) log.Print(res2) sep0 := python3.PyLong_FromGoInt(0) cpos := res2.CallMethodArgs("plot_nodal_solution", sep0) //显示到窗口 log.Print(cpos) sep2 := python3.PyUnicode_FromString("hexrst3.vtk") res3 := res2.CallMethodArgs("save_as_vtk", sep2) log.Print(res3)

注意到没有,是先导入这个代码文件plot.py,然后再获取py代码里引入的模块aaa,开始使用aaa里的read_binary方法,用callmethodargs,方法名称写在括号里,参数写在方法名称后面。代码有点乱,看仔细点就清楚了。好了,就是下面这个效果而已。

这个3d图可是可以转动的哦,vtk真是厉害。

有时候编译go又出现#include **.h 找不到错误,则运行bat文件,注释掉安装python部分。

注释掉(rem)build.bat中安装python部分,如下

@echo off setlocal set destdir=c:\dist rem curl -L https://www.python.org/ftp/python/3.7.9/python-3.7.9-amd64.exe -o %tmp%\python-setup.exe rem %tmp%\python-setup.exe /quiet TargetDir=c:\py Include_lib=1 Include_symbols=1 CompileAll=1 Include_dev=1 PrependPath=0 AssociateFiles=0 Shortcuts=0 Include_doc=0 Include_test=0 Include_tools=0 Include_pip=0 Include_launcher=0 Include_exe=1 rem curl -L https://www.python.org/ftp/python/3.7.9/python-3.7.9-embed-amd64.zip -o %tmp%\python-min.zip mkdir "%destdir%" powershell -c "Expand-Archive -Path \"${env:tmp}\python-min.zip\" -DestinationPath \"${env:destdir}\" -force" choco install /y pkgconfiglite set PKG_CONFIG_PATH=%~dp0pkg-config go build -o "%destdir%"

然后点击运行build.bat即可修复。

http://www.jsqmd.com/news/1268822/

相关文章:

  • Android 项目架构设计:从 MVC 到 MVI 的演进与实践
  • BG3ModManager:从模组混乱到游戏秩序,你的博德之门3模组管理革命
  • 三星固件下载神器Bifrost:跨平台免费下载解密工具完整指南
  • 联系方式:13393032100|2026年石家庄欧米茄手表回收 周边县城上门现场打款 - 小何收的顶
  • 智能体安全防护:三层架构与对齐工程实践
  • UE4 C++开发环境搭建:基于Rider的完整避坑指南与调试实战
  • 国家中小学智慧教育平台电子课本下载神器:tchMaterial-parser免费快速指南
  • 天门全封闭武校排名,武当山精武武校管理模式揭秘 - 圣龙武术朱老师
  • GetQzonehistory:如何快速找回QQ空间全部历史说说的完整教程
  • 长篇写作不翻车,国产模型怎么选?——基于50万字实测数据的选型避坑指南,错过再等半年
  • 3分钟上手Sketch批量文本替换神器:告别繁琐手动修改
  • 2026 年沈阳 GEO 优化公司选择指南及服务选型实用攻略 - 章鱼智讯
  • 2026西安二手手表回收行情解析:多品牌保值溢价对比+五大平台实测测评 - 奢侈品回收探店ing
  • 开源AI视频平台:GB28181与RTSP协议解析及低代码实践
  • 【Python课程设计/毕业设计】基于 Python 的停车场车位动态监测与运营数据分析系统【附源码、数据库、万字文档】
  • AI系统设计中的伦理考量与关键技术实践
  • VideoSrt:Windows平台视频字幕自动生成的终极解决方案
  • 潜江正规文武学校有哪些?武当山精武武校办学资质详解 - 圣龙武术朱老师
  • 为什么92%的AI视频项目在第3步失败?——端到端Pipeline中被忽视的时序对齐陷阱与跨模态校准方案(内部白皮书首公开)
  • UE4布娃娃物理系统实战:告别面条人,实现真实角色死亡动画
  • 南宁易奢福欧米茄手表回收|全城统一报价闲置腕表快速出手 - 回收奢侈品探店测评
  • GEO AI技术在成都本地化SEO营销中的实践应用
  • 2026北京通州管道疏通哪家好利扬靠谱上门疏通避坑指南 - 余生黄金回收
  • AI自改进系统的复杂度边界与控制策略
  • 3步解决英文界面难题:PowerToys中文配置的终极指南
  • 无锡产业的“AI可见”突围:当万亿集群遇上生成式引擎优化 - 信息热点
  • 【Springboot毕设全套源码+文档】基于springboot的三七原产地销售平台的设计与实现(丰富项目+远程调试+讲解+定制)
  • 5大革新特性:基于LCU API的英雄联盟全能工具箱技术深度解析
  • 曲靖低压高压电工焊工高处作业培训学校,推荐到云南曲靖滇工职业技能培训学校 - 资讯报道
  • AI辅助技术写作:消除机械感与提升真实性的实践