Home > Backend Development > Golang > How do you execute external commands and retrieve their output in Go?

How do you execute external commands and retrieve their output in Go?

DDD
Release: 2024-11-02 01:35:31
Original
318 people have browsed it

How do you execute external commands and retrieve their output in Go?

Invoking External Commands in Go

In Go, accessing external commands and ensuring their completion before proceeding with subsequent operations is essential. To address this need, the exec package provides a robust mechanism.

Command Execution with Waiting

The exec.Command function allows you to create a new command with specified arguments. To run the command and wait for its completion before executing the next statement, use the Run method.

<code class="go">cmd := exec.Command("yourcommand", "some", "args")
if err := cmd.Run(); err != nil {
    fmt.Println("Error:", err)
}</code>
Copy after login

Retrieving Command Output

If you only require the output of the external command, you can utilize the Output method instead of Run. This method returns a byte array containing the command's standard output.

<code class="go">cmd := exec.Command("yourcommand", "some", "args")
output, err := cmd.Output()
if err != nil {
    fmt.Println("Error:", err)
} else {
    fmt.Println("Output:", string(output))
}</code>
Copy after login

The above is the detailed content of How do you execute external commands and retrieve their output in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template