Os.exec Package Introduction to go language

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Reprinted from: http://www.unjeep.com/q/586059486.htm


The Exec package executes the external command, which will be OS. The startprocess is packaged to make it easier to map to stdin and stdout and to use pipe to connect I/O.

Func lookpath (File string) (string, error)//lookpath finds the section in the environment variable executes the binary file, if file contains a slash, it is directly based on the absolute path or relative to the relative path of the directory to find

Func main () {f, err: = Exec. Lookpath ("ls") if err! = Nil {fmt. PRINTLN (Err)}fmt. Println (f)//  /bin/ls}

type CMD//Represents an external command that is being prepared or is running

Type CMD struct {path string//path to run command, absolute path or relative path args []string//Command parameter env []string// The process environment, if the environment is empty, uses the current process's environment Dir string//Specifies the command's working directory, and if Dir is empty, Comman runs stdin io in the current directory where the calling process resides. Reader//Standard input, if stdin is nil, the process reads from the NULL device (OS. Devnull), stdin can also be a file, otherwise it will open a goroutine in the run process to//read the standard input stdout IO. Writer//Standard output stderr io. Writer//Error output, if these two (stdout and stderr) are empty, the command runtime will respond to the file description connect prompt to the OS. Devnullextrafiles []*os. File sysprocattr *syscall. Sysprocattrprocess *os. The process//process is a bottom-level procedure that launches only one processstate *os. Processstate//processstate contains information about an exit process that is generated when a process calls wait or run. }

The func command (name string, arg ... string) *cmd//command returns a CMD structure to execute a command with related parameters, which only sets the path and args parameters in the CMD structure, if the name parameter does not contain a path delimiter , command uses Lookpath to solve the path problem, otherwise the direct use of the Name;args directly following the command commands, so in the args are not allowed to add commands.

Func main () {cmd: = Exec.command ("tr", "A-Z", "A-Z") cmd. Stdin = strings. Newreader ("some input") var out bytes. Buffercmd.stdout = &outerr: = cmd. Run () if err! = Nil {log. Fatal (Err)}fmt. Printf ("In all caps:%q\n"), out. String ())//in All caps: "SOME INPUT"}

Func (c *cmd) Combinedoutput () ([]byte, error)//Run command and return standard output and standard error

Func main () {cmd: = Exec.command ("ls")//view current directory under file out, err: = Cmd.combinedoutput () if err! = Nil {fmt. PRINTLN (Err)}fmt. Println (String (out))}


func (c *cmd) output () ([]byte, error)//Run command and return its standard output

Func main () {cmd: = Exec.command ("ls")///view the current directory under file out, err: = cmd. Output () if err! = Nil {fmt. PRINTLN (Err)}fmt. Println (String (out))}
Note: output () and combinedoutput () cannot be used at the same time, because the command standard output can only have one, and the use of the words will be defined two, will be an error

func (c *cmd) Run () Error// start specifying the command and wait for his execution to finish returns nil if the command completes successfully, otherwise the side generates an error
func (c *cmd) Start () Error// cause a command to execute, but not until he finishes, this is different from the Run command. Then use the wait method to wait for the command to complete and release the response resource

Func main () {cmd: = Exec.command ("ls") cmd. Stdout = OS. Stdout//cmd. Run () fmt. Println (cmd. Start ())//exec:already started}
Note: A command can only use one of the start commands in Start () or run (), not both.

func (c *cmd) stderrpipe () (IO. Readcloser, error)//stderrpipe returns a pipe that connects to the command's standard error, and when command commands exits, wait closes the pipe
func (c *cmd) stdinpipe () (IO. Writecloser, error)//stdinpipe returns a piping pipe that is connected to the command standard input


Package Mainimport ("FMT" "OS" "Os/exec") func main () {cmd: = Exec.command ("Cat") stdin, err: = cmd. Stdinpipe () if err! = Nil {fmt. PRINTLN (Err)}_, err = stdin. Write ([]byte ("Tmp.txt")) if err! = Nil {fmt. PRINTLN (Err)}stdin. Close () cmd. Stdout = OS. Stdout     //terminal standard output Tmp.txtcmd.Start ()}

func (c *cmd) stdoutpipe () (IO. Readcloser, error)//stdoutpipe returns a piping pipe that is connected to the command standard output

Func main () {cmd: = Exec.command ("ls") stdout, err: = cmd. Stdoutpipe ()//stdoutcmd that points to the cmd command. Start () content, err: = Ioutil. ReadAll (stdout) if err! = Nil {fmt. PRINTLN (Err)}fmt. Println (string     content)//output LS command to see what is seen}


func (c *cmd) wait () error//wait waits for the command to exit, he must be used with start, if the command can be executed smoothly and exit successfully returns nil, otherwise the error will be returned, where Wait will be dropped All resources related to the cmd command


Type error//error return section execution binary file name not able to perform the cause of the errors

Type error struct {Name stringerr  error}


Func (e *error) Error () string


Type exiterror//An error that the command cannot exit normally

Type exiterror struct {    *os. Processstate}

func (E *exiterror) Error () string
Related Article

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.