佳木斯湛栽影视文化发展公司

主頁 > 知識庫 > Go語言調(diào)用Shell與可執(zhí)行文件的實現(xiàn)

Go語言調(diào)用Shell與可執(zhí)行文件的實現(xiàn)

熱門標簽:AI電銷 鐵路電話系統(tǒng) Linux服務器 呼叫中心市場需求 服務外包 地方門戶網(wǎng)站 百度競價排名 網(wǎng)站排名優(yōu)化

os/exec包可用于調(diào)用外部命令,可以使用管道連接輸入輸出,并支持阻塞與非阻塞方式執(zhí)行命令。

os/exec包中關(guān)鍵的類型為Cmd,以下介紹的所有方法皆服務于該類型:

func Command(name string, arg ...string) *Cmd
方法返回一個*Cmd, 用于執(zhí)行name指定的程序(攜帶arg參數(shù))

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

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

func (c *Cmd) Wait() error
該方法會阻塞直到Cmd中的命令執(zhí)行完成,但該命令必須是被Start方法開始執(zhí)行的

func (c *Cmd) Output() ([]byte, error)
執(zhí)行Cmd中包含的命令,并返回標準輸出的切片

func (c *Cmd) CombinedOutput() ([]byte, error)
執(zhí)行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中的命令被啟動后連接到其標準錯誤

普通調(diào)用示例:

調(diào)用Shell命令或可執(zhí)行文件

演示在當前目錄創(chuàng)建一個空文件

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.")
}

一般不建議使用這種默認方式調(diào)用Shell腳本:

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

因為這種方式實際的執(zhí)行結(jié)果和命令行執(zhí)行#sh my_shell.sh一樣,如果你的Shell腳本不滿足sh的規(guī)范,就會調(diào)用失敗。

調(diào)用Shell腳本

設置bash來調(diào)用指定Shell腳本,dir_size.sh為我們測試用的Shell腳本。調(diào)用完成后打印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示例文件內(nèi)容如下,用于輸出當前目錄的大?。?/p>

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

Go程序運行結(jié)果:

[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的字符串,并使用管道連接標準輸出,打印運行結(jié)果:

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程序運行結(jié)果:

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

阻塞/非阻塞方式調(diào)用

文章開頭方法介紹處已經(jīng)介紹的很清楚,且前面示例都有涉及,就不另行說明了。

參考文檔:
GoLang標準庫文檔

到此這篇關(guān)于Go語言調(diào)用Shell與可執(zhí)行文件的實現(xiàn)的文章就介紹到這了,更多相關(guān)Go語言調(diào)用Shell內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • linux中用shell快速安裝配置Go語言的開發(fā)環(huán)境

標簽:黃山 衡水 仙桃 崇左 銅川 蘭州 湘潭 湖南

巨人網(wǎng)絡通訊聲明:本文標題《Go語言調(diào)用Shell與可執(zhí)行文件的實現(xiàn)》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡,涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    临海市| 陈巴尔虎旗| 墨脱县| 云浮市| 公安县| 肇源县| 鹤岗市| 邯郸市| 仁寿县| 凉城县| 平凉市| 石城县| 论坛| 长治市| 淮北市| 昆明市| 浪卡子县| 新河县| 辽中县| 寿宁县| 自贡市| 怀仁县| 永和县| 新河县| 河东区| 温宿县| 建始县| 南靖县| 即墨市| 冀州市| 格尔木市| 长岛县| 青铜峡市| 崇明县| 永宁县| 桦川县| 随州市| 靖远县| 中牟县| 嘉禾县| 洛隆县|