开发者

exec.Run - What's wrong with this Go program?

开发者 https://www.devze.com 2023-01-16 06:54 出处:网络
Isn\'t this Golang program supposed to output a directory listing to stdout? 开发者_如何学JAVAIt compiles ok, but does nothing.

Isn't this Golang program supposed to output a directory listing to stdout? 开发者_如何学JAVAIt compiles ok, but does nothing.

package main

import "exec"

func main() {
  argv := []string{"-la"}
  envv := []string{}
  exec.Run("ls", argv, envv, "", exec.DevNull, exec.PassThrough, exec.MergeWithStdout)
}


this works:

package main
import "exec"

func main() {
  cmd, err := exec.Run("/bin/ls", []string{"/bin/ls", "-la"}, []string{}, "", exec.DevNull, exec.PassThrough, exec.PassThrough)
  if (err != nil) {
    return
  }
  cmd.Close()
}


You could also do it in native go using: ioutil.ReadDir(dir), like so:

//listdir.go
package main

import (
    "os"
    "io/ioutil"
    "fmt"
)

func ListDir(dir string) ([]os.FileInfo, error) {
    return ioutil.ReadDir(dir)
}

func main() {
    dir := "./"
    if len(os.Args) > 1 {
        dir = os.Args[1]
    }
    fi, err := ListDir(dir)
    if err != nil {
        fmt.Println("Error", err)
    }

    for _, f := range fi {
        d := "-"
        if f.IsDir() { d = "d" }
        fmt.Printf("%s %o %d %s %s\n", d, f.Mode() & 0777, f.Size(), f.ModTime().Format("Jan 2 15:04"), f.Name())
    }
}

Checkout the documentation available for ioutil and os packages.


By default exec.Command will leave standard input, output and error connected to /dev/null. So, your 'ls' command is running fine but the output is just being thrown away. If you add:

cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr

before the exec.Run call then your output will go where you probably expect it.


exec.Run replaces your program with the one it executes -- it never returns to your app. This means that when 'cd' completes, it will exit as normal, and the only effect should be of changing the directory; 'ls' will never run.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号