Golang+linux+pipline

Source: Internet
Author: User

Golang can invoke commands in Linux via the [os/exec] package, however, for pipelines in Linux ("|" ) but cannot be used directly. So the interface for writing a pipe is as follows.

Func pipline (Cmds ... *exec. CMD) ([]byte, []byte, error) {    //At least one command    ifLen (CMDS) <1 {        returnNil , nil, nil}varoutput bytes. Buffervarstderr bytes. BuffervarErr error Maxindex:= Len (CMDS)-1Cmds[maxindex]. Stdout= &output CMDS[MAXINDEX]. Stderr= &stderr forI, cmd: =Range Cmds[:maxindex] {ifi = =Maxindex { Break} cmds[i+1]. Stdin, err =cmd. Stdoutpipe ()ifErr! =Nil {returnNil, nil, err}} //Start each command     for_, cmd: =range Cmds {err:=cmd. Start ()ifErr! =Nil {returnoutput. Bytes (), stderr. Bytes (), err}}//Wait for each command to complete     for_, cmd: =range Cmds {err:=cmd. Wait ()ifErr! =Nil {returnoutput. Bytes (), stderr. Bytes (), err}}returnoutput. Bytes (), stderr. Bytes (), nil}
View Code

Interface Invocation Method:

    //Linux COMAND:DF | grep-w "/" | cut-d "%",-F 1DF: = Exec.command ("DF") grep:= Exec.command ("grep","- W","/") Cut:= Exec.command ("Cut","- D","%","- F","1") result, _, Err:=Utils. Pipline (DF, grep, cut)ifErr! =Nil {log. Error (ERR)return    }     //Output Final ResultFmt. Println (string(result))
View Code

Golang+linux+pipline

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.