乐闻世界logo
搜索文章和话题

How to run a CLI command from Go?

1个答案

1

In Go, running CLI commands can be achieved using the os/exec package. This package provides functionality for executing and managing external commands. By using the exec.Command function, we can create an instance of the *exec.Cmd struct to represent an external command. We can then use methods such as Run, Start, or Output to execute the command.

Steps and Examples

  1. Import the os/exec package

    At the beginning of your Go file, import the necessary package.

    go
    import "os/exec"
  2. Create the command

    Use the exec.Command function to create the command. This function accepts the command name and parameters as input.

    go
    cmd := exec.Command("echo", "Hello, World!")
  3. Run the command

    Use the Run method to execute the command. This will block until the command completes.

    go
    err := cmd.Run() if err != nil { log.Fatalf("cmd.Run() failed with %s\n", err) }

    To capture the command's output, use the Output method:

    go
    output, err := cmd.Output() if err != nil { log.Fatal(err) } fmt.Println(string(output))

Complete Example Code

The following is a complete example demonstrating how to run a simple echo command and print its output.

go
package main import ( "fmt" "log" "os/exec" ) func main() { // Create the command cmd := exec.Command("echo", "Hello, World!") // Run the command and capture the output output, err := cmd.Output() if err != nil { log.Fatal(err) } // Print the command's output fmt.Println(string(output)) }

Running the above program will output:

shell
Hello, World!

This example demonstrates how to run CLI commands in Go and handle their output. Using similar methods, you can run different CLI commands and handle the output or errors as needed.

2024年10月28日 20:44 回复

你的答案