前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >golang调用python3,并使用python模块中的方法

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

作者头像
hotqin888
发布2022-03-10 15:24:21
3.3K0
发布2022-03-10 15:24:21
举报
文章被收录于专栏:hotqin888的专栏hotqin888的专栏

因项目需要,很多代码和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 python get-pip.py # 运行安装脚本

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

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

Win下:python get-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/simple ansys-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/simple ansys-dpf-post

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

9.go-py3例子

Golang中调用Python3 - 知乎

调用python模块中的方法

比如,一个python的代码如下

代码语言:javascript
复制
# 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里怎么做呢?

代码语言:javascript
复制
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部分,如下

代码语言:javascript
复制
@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即可修复。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • py3安装方法
    • 1.先安装chocolatey
      • 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
                  • 8.开始安装依赖包:设置国内代理,否则超级慢
                    • 9.go-py3例子
                    • 调用python模块中的方法
                    领券
                    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档