Go语言调用Shell与可执行文件的实现

作者:莫问君心 时间:2024-02-06 17:03:44 

os/exec包可用于调用外部命令,可以使用管道连接输入输出,并支持阻塞与非阻塞方式执行命令。

os/exec包中关键的类型为Cmd,以下介绍的所有方法皆服务于该类型:

func Command(name string, arg ...string) *Cmd
方法返回一个*Cmd, 用于执行name指定的程序(携带arg参数)

func (c *Cmd) Run() error
执行Cmd中包含的命令,阻塞直到命令执行完成

func (c *Cmd) Start() error
执行Cmd中包含的命令,该方法立即返回,并不等待命令执行完成

func (c *Cmd) Wait() error
该方法会阻塞直到Cmd中的命令执行完成,但该命令必须是被Start方法开始执行的

func (c *Cmd) Output() ([]byte, error)
执行Cmd中包含的命令,并返回标准输出的切片

func (c *Cmd) CombinedOutput() ([]byte, error)
执行Cmd中包含的命令,并返回标准输出与标准错误合并后的切片

func (c *Cmd) StdinPipe() (io.WriteCloser, error)
返回一个管道,该管道会在Cmd中的命令被启动后连接到其标准输入

func (c *Cmd) StdoutPipe() (io.ReadCloser, error)
返回一个管道,该管道会在Cmd中的命令被启动后连接到其标准输出

func (c *Cmd) StderrPipe() (io.ReadCloser, error)
返回一个管道,该管道会在Cmd中的命令被启动后连接到其标准错误

普通调用示例:

调用Shell命令或可执行文件

演示在当前目录创建一个空文件


package main

import (
 "fmt"
 "os/exec"
)

func main(){
 cmd := exec.Command("touch", "test_file")

err := cmd.Run()
 if err != nil {
   fmt.Println("Execute Command failed:" + err.Error())
   return
 }

fmt.Println("Execute Command finished.")
}

一般不建议使用这种默认方式调用Shell脚本:


cmd := exec.Command("my_shell.sh")

因为这种方式实际的执行结果和命令行执行#sh my_shell.sh一样,如果你的Shell脚本不满足sh的规范,就会调用失败。

调用Shell脚本

设置bash来调用指定Shell脚本,dir_size.sh为我们测试用的Shell脚本。调用完成后打印Shell脚本的标准输出到控制台。


package main

import (
 "fmt"
 "os/exec"
)

func main(){
 command := `./dir_size.sh .`
 cmd := exec.Command("/bin/bash", "-c", command)

output, err := cmd.Output()
 if err != nil {
   fmt.Printf("Execute Shell:%s failed with error:%s", command, err.Error())
   return
 }
 fmt.Printf("Execute Shell:%s finished with output:\n%s", command, string(output))
}

dir_size.sh示例文件内容如下,用于输出当前目录的大小:


#!/bin/bash
du -h --max-depth=1 $1

Go程序运行结果:


[root@localhost opt]# ll
total 2120
-rwx------. 1 root root   36 Jan 22 16:37 dir_size.sh
-rwx------. 1 root root 2152467 Jan 22 16:39 execCommand
drwxrwxr-x. 11 1000 1000  4096 Jul 12 2017 kibana
drwx------. 2 root root  4096 Jan 16 10:45 sftpuser
drwx------. 3 root root  4096 Jan 22 16:41 upload
[root@localhost opt]# ./execCommand
Execute Shell:./dir_size.sh . finished with output:
4.0K  ./sftpuser
181M  ./kibana
1.1G  ./upload
1.2G  .

使用输入输出Pipe

演示使用管道连接到grep命令的标准输入,过滤包含test的字符串,并使用管道连接标准输出,打印运行结果:


package main

import (
 "fmt"
 "io/ioutil"
 "os/exec"
)

func main(){
 cmd := exec.Command("/bin/bash", "-c", "grep test")

stdin, _ := cmd.StdinPipe()
 stdout, _ := cmd.StdoutPipe()

if err := cmd.Start(); err != nil{
   fmt.Println("Execute failed when Start:" + err.Error())
   return
 }

stdin.Write([]byte("go text for grep\n"))
 stdin.Write([]byte("go test text for grep\n"))
 stdin.Close()

out_bytes, _ := ioutil.ReadAll(stdout)
 stdout.Close()

if err := cmd.Wait(); err != nil {
   fmt.Println("Execute failed when Wait:" + err.Error())
   return
 }

fmt.Println("Execute finished:" + string(out_bytes))
}

Go程序运行结果:

[root@localhost ~]# ./execCommand
Execute finished:go test text for grep

阻塞/非阻塞方式调用

文章开头方法介绍处已经介绍的很清楚,且前面示例都有涉及,就不另行说明了。

参考文档:
GoLang标准库文档

来源:https://www.jianshu.com/p/dd8a113b02a3

标签:Go语言,调用,Shell
0
投稿

猜你喜欢

  • 浅析Python语言自带的数据结构有哪些

    2022-01-14 04:08:44
  • 解决pycharm运行时interpreter为空的问题

    2022-04-01 22:56:39
  • SQL Server修改标识列方法 如自增列的批量化修改

    2012-06-06 19:42:35
  • Python 对象序列化与反序列化之pickle json详细解析

    2021-09-06 23:44:06
  • MySQL定时任务不能正常执行的原因分析及解决方法

    2024-01-23 16:28:24
  • Python Selenium XPath根据文本内容查找元素的方法

    2022-02-18 12:55:16
  • python中如何提高图像质量

    2023-05-17 17:02:03
  • python安装cx_Oracle和wxPython的方法

    2022-07-31 11:33:04
  • Python内存映射文件读写方式

    2023-07-07 23:32:36
  • 详解python学习笔记之解释器

    2023-09-15 15:28:26
  • 使用Python为中秋节绘制一块美味的月饼

    2023-06-30 17:36:10
  • 推荐系统MostPopular算法的Python实现方式

    2022-04-21 14:44:24
  • vue3.0 上手体验

    2024-04-30 10:26:49
  • Oracle中命名块之存储过程的详解及使用方法

    2023-07-15 00:28:23
  • 如何将python文件打包成exe可运行文件

    2022-06-29 19:01:17
  • MySQL批量更新的四种方式总结

    2024-01-13 17:53:08
  • 2009淘宝网动画节日LOGO第一季

    2009-05-18 19:11:00
  • python判断文件是否存在,不存在就创建一个的实例

    2022-04-29 02:28:55
  • 详解用Python调用百度地图正/逆地理编码API

    2021-06-01 16:35:39
  • 三种SQL分页法

    2010-05-07 11:03:00
  • asp之家 网络编程 m.aspxhome.com