12.1 执行脚本
如下golang可以执行python脚本
package main
import (
"fmt"
"os/exec"
)
func main() {
cmd := exec.Command("/usr/local/bin/python3.9", "/Users/haha/GolandProjects/awesomeProject5/test.py")
// 命令的错误输出和标准输出都连接到同一个管道
stdout, err := cmd.StdoutPipe()
cmd.Stderr = cmd.Stdout
if err != nil {
return
}
err = cmd.Start()
if err != nil {
return
}
// 从管道中实时获取输出并打印到终端
for {
tmp := make([]byte, 1024)
_, err := stdout.Read(tmp)
fmt.Print(string(tmp))
if err != nil {
break
}
}
if err = cmd.Wait(); err != nil {
return
}
}
python脚本如下:
#!usr/bin/python3
assert 3 == 4
执行结果:
Traceback (most recent call last):
File "/Users/haha/GolandProjects/awesomeProject5/test.py", line 2, in <module>
assert 3 == 4
AssertionError
err = exit status 1
12.2 type func()
与type struct很类似,golang还支持type func()来定义函数,如type myFunc func(int) int,意思是自定义了一个叫myFunc的函数类型,这个函数的签名必须符合输入为int,输出为int,下面看例子:
package main
import (
"fmt"
)
type myFun func(a, b int) int
func sum(a, b int) int {
return a + b
}
func main() {
newFunc := myFun(sum)
c := newFunc(2, 3)
fmt.Println("c = ", c)
}
结果:
c = 5
12.3 获取环境变量
package main
import (
"fmt"
"os"
)
func main() {
goPath := os.Getenv("GOPATH")
fmt.Println("goPath = ", goPath)
}
结果:
goPath = /Users/bytedance/go
12.4 获取本地ip地址
package main
import (
"fmt"
"net"
"os"
)
func main() {
addrs, err := net.InterfaceAddrs()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
for _, address := range addrs {
// 检查ip地址判断是否回环地址
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
fmt.Println(ipnet.IP.String())
}
}
}
}
结果
10.78.21.144