package main
import (
"bytes"
"fmt"
//"log"
"os/exec"
)
func main() {
cmd := exec.Command("dir")
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
fmt.Printf("cmd.Run: %s failed: %s\n", err, err)
}
outStr, errStr := string(stdout.Bytes()), string(stderr.Bytes())
if len(errStr) > 1 {
fmt.Printf("out:\n%s\nerr:\n%s\n", outStr, errStr)
}
fmt.Printf(outStr)
}
*Hi guys, whenever I try to run this file with go it shows me This error "cmd.Run: exec: "dir": executable file not found in %PATH% failed:". I have golang in my PATH but it still failed *
dir is not an executable file in Windows, rather it is an internal command of Command prompt. You need to pass dir to command prompt. Your command would look like this:
cmd.exe /c dir
You can implement it like this:
args := strings.Split("/c dir"," ")
cmd := exec.Command("cmd.exe",args...)
Pass your command line arguments like this, strings.Split() will split "/c dir" into all substrings separated by " " and returns a slice of the substrings between those separators.
Also if you need to print dir of a specific location you can set the working directory of the command:
cmd.Dir = filepath.Join("C:","Windows")
filepath.Join joins any number of path elements into a single path, separating them with an OS specific Separator.
Add the following packages into your file
import ( "os" "path/filepath" "strings" )
To print the result you can connect your output and error to the standard output, and standard error.
cmd.Stdout = os.Stdout
cmd.Stderr = &os.Stderr
Your overall code would be:
package main
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
)
func main() {
args := strings.Split("/c dir"," ")
cmd := exec.Command("cmd.exe",args...)
cmd.Dir = filepath.Join("C:","Windows")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
fmt.Printf("cmd.Run: %s failed: %s\n", err, err)
}
}