本文整理汇总了Golang中exec.Command函数的典型用法代码示例。如果您正苦于以下问题:Golang Command函数的具体用法?Golang Command怎么用?Golang Command使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Command函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: RunExternalAndStdout
func RunExternalAndStdout(cmd, wd string, argv []string) (stdout []byte, err os.Error) {
argv = SplitArgs(argv)
var c *exec.Cmd
if len(argv) > 0 {
c = exec.Command(cmd, argv...)
} else {
c = exec.Command(cmd)
}
c.Dir = wd
c.Env = os.Environ()
bStdout := bytes.NewBuffer(nil)
bStderr := bytes.NewBuffer(nil)
c.Stdout = bStdout
c.Stderr = bStderr
err = c.Run()
if wmsg, ok := err.(*os.Waitmsg); ok {
if wmsg.ExitStatus() != 0 {
err = os.NewError(fmt.Sprintf("command: %s %v\n%s\n", cmd, argv, bStderr.String()))
} else {
err = nil
}
} else {
stdout = bStdout.Bytes()
}
return
}
示例2: MoveChapter
func MoveChapter(source string, dest string, resize bool) {
files, _ := ioutil.ReadDir(source)
for _, v := range files {
if !validImage(v.Name) {
fmt.Println("ignorando " + source + "/" + v.Name)
continue
}
newName := ClearPageName(v.Name)
canResize, needR := needResize(source + "/" + v.Name)
var err os.Error
cmd := "/usr/local/bin/convert"
if resize && canResize {
if needR {
_, err = exec.Command(cmd, "-resize", "900x1600", "-quality", "50", source+"/"+v.Name, dest+"/"+newName).CombinedOutput()
fmt.Println("Recodificando e diminuindo " + source + "/" + v.Name + " para " + dest + "/" + newName)
} else {
_, err = exec.Command(cmd, "-quality", "50", source+"/"+v.Name, dest+"/"+newName).CombinedOutput()
fmt.Println("recodificando " + source + "/" + v.Name + " para " + dest + "/" + newName)
}
if err != nil {
fmt.Println("falha ao mover e recodificar arquivo " + source + "/" + v.Name + ": " + err.String())
os.Exit(1)
}
} else {
/*if canResize{
fmt.Println("movendo " + source + "/" + v.Name + " para " + dest + "/" + newName)
}else{
}*/
if ext := strings.ToLower(path.Ext(v.Name)); ext == ".png" {
fmt.Println("não foi possível codificar, movendo " + source + "/" + v.Name + " para " + dest + "/" + newName)
if err = os.Rename(source+"/"+v.Name, dest+"/"+newName); err != nil {
fmt.Println("falha ao mover " + source + "/" + v.Name + " para " + dest + "/" + newName + ": " + err.String())
}
} else {
fmt.Println("recodificando " + source + "/" + v.Name + " para " + dest + "/" + newName)
_, err = exec.Command(cmd, "-quality", "50", source+"/"+v.Name, dest+"/"+newName).CombinedOutput()
if err != nil {
fmt.Println("não foi possível codificar, movendo " + source + "/" + v.Name + " para " + dest + "/" + newName)
if err = os.Rename(source+"/"+v.Name, dest+"/"+newName); err != nil {
fmt.Println("falha ao mover " + source + "/" + v.Name + " para " + dest + "/" + newName + ": " + err.String())
}
}
}
}
// time.Sleep(1000000000)
}
}
示例3: MakeRaw
/*
Set the standard in and out screens to raw mode.
Always call ResetRaw() when you are done.
Post:
ResetRaw() will reset standard in and out to pre-raw settings
*/
func MakeRaw() {
c := exec.Command("stty", "raw")
set_exec(c)
c.Run()
ResetRaw = func() {
c := exec.Command("stty", "-raw")
set_exec(c)
c.Run()
}
}
示例4: OpenURL
func OpenURL(url string) os.Error {
if runtime.GOOS == "windows" {
return exec.Command("cmd.exe", "/C", "start "+url).Run()
}
if runtime.GOOS == "darwin" {
return exec.Command("open", url).Run()
}
return exec.Command("xdg-open", url).Run()
}
示例5: BenchmarkCFuseThreadedStat
func BenchmarkCFuseThreadedStat(b *testing.B) {
log.Println("benchmarking CFuse")
lines := GetTestLines()
unique := map[string]int{}
for _, l := range lines {
unique[l] = 1
dir, _ := filepath.Split(l)
for dir != "/" && dir != "" {
unique[dir] = 1
dir = filepath.Clean(dir)
dir, _ = filepath.Split(dir)
}
}
out := []string{}
for k, _ := range unique {
out = append(out, k)
}
f, err := ioutil.TempFile("", "")
CheckSuccess(err)
sort.Strings(out)
for _, k := range out {
f.Write([]byte(fmt.Sprintf("/%s\n", k)))
}
f.Close()
log.Println("Written:", f.Name())
mountPoint, _ := ioutil.TempDir("", "stat_test")
wd, _ := os.Getwd()
cmd := exec.Command(wd+"/cstatfs", mountPoint)
cmd.Env = append(os.Environ(), fmt.Sprintf("STATFS_INPUT=%s", f.Name()))
cmd.Start()
bin, err := exec.LookPath("fusermount")
CheckSuccess(err)
stop := exec.Command(bin, "-u", mountPoint)
CheckSuccess(err)
defer stop.Run()
for i, l := range lines {
lines[i] = filepath.Join(mountPoint, l)
}
// Wait for the daemon to mount.
time.Sleep(0.2e9)
ttl := 1.0
log.Println("N = ", b.N)
threads := runtime.GOMAXPROCS(0)
results := TestingBOnePass(b, threads, ttl*1.2, lines)
AnalyzeBenchmarkRuns(results)
}
示例6: Run
// Run executes the Cmd.
func (c *Cmd) Run() error {
if c.Args[0] == "mkdir" {
for _, p := range c.Output {
if err := os.MkdirAll(p, 0777); err != nil {
return fmt.Errorf("command %q: %v", c, err)
}
}
return nil
}
out := new(bytes.Buffer)
cmd := exec.Command(c.Args[0], c.Args[1:]...)
cmd.Dir = c.Dir
cmd.Env = c.Env
cmd.Stdout = out
cmd.Stderr = out
if c.Stdout != "" {
f, err := os.Create(c.Stdout)
if err != nil {
return err
}
defer f.Close()
cmd.Stdout = f
}
if err := cmd.Run(); err != nil {
return fmt.Errorf("command %q: %v\n%v", c, err, out)
}
return nil
}
示例7: RunExternalDump
func RunExternalDump(cmd, wd string, argv []string, dump *os.File) (err error) {
argv = SplitArgs(argv)
if Verbose {
fmt.Printf("%s\n", argv)
}
c := exec.Command(cmd, argv[1:]...)
c.Dir = wd
c.Env = os.Environ()
c.Stdout = dump
c.Stderr = os.Stderr
err = c.Run()
if wmsg, ok := err.(*os.Waitmsg); ok {
if wmsg.ExitStatus() != 0 {
err = errors.New(fmt.Sprintf("%v: %s\n", argv, wmsg.String()))
} else {
err = nil
}
}
return
}
示例8: run
// run runs the command argv, resolving argv[0] if necessary by searching $PATH.
// It provides input on standard input to the command.
func run(argv []string, input []byte) (out string, err os.Error) {
if len(argv) < 1 {
err = os.EINVAL
goto Error
}
prog, ok := lookPathCache[argv[0]]
if !ok {
prog, err = exec.LookPath(argv[0])
if err != nil {
goto Error
}
lookPathCache[argv[0]] = prog
}
cmd := exec.Command(prog, argv[1:]...)
if len(input) > 0 {
cmd.Stdin = bytes.NewBuffer(input)
}
bs, err := cmd.CombinedOutput()
if err == nil {
return string(bs), nil
}
Error:
err = &runError{dup(argv), err}
return
}
示例9: TestRmRf
func TestRmRf(t *testing.T) {
t.Log("TestRemoveAll")
wd, clean := setupUfs(t)
defer clean()
err := os.MkdirAll(wd+"/ro/dir/subdir", 0755)
CheckSuccess(err)
contents := "hello"
fn := wd + "/ro/dir/subdir/y"
err = ioutil.WriteFile(fn, []byte(contents), 0644)
CheckSuccess(err)
cmd := exec.Command("/bin/rm", "-rf", wd+"/mount/dir")
err = cmd.Run()
if err != nil {
t.Fatal("rm -rf returned error:", err)
}
for _, f := range []string{"dir/subdir/y", "dir/subdir", "dir"} {
if fi, _ := os.Lstat(filepath.Join(wd, "mount", f)); fi != nil {
t.Errorf("file %s should have disappeared: %v", f, fi)
}
}
names, err := Readdirnames(wd + "/rw/DELETIONS")
CheckSuccess(err)
if len(names) != 3 {
t.Fatal("unexpected names", names)
}
}
示例10: main
func main() {
ps := exec.Command("ps", "-e", "-opid,ppid,comm")
output, _ := ps.Output()
child := make(map[int]*vector.IntVector)
for i, s := range strings.Split(string(output), "\n") {
if i == 0 || len(s) == 0 { // Kill first and last line
continue
}
f := strings.Fields(s)
fpp, _ := strconv.Atoi(f[1]) // the parent's pid
fp, _ := strconv.Atoi(f[0]) // the child's pid
if _, present := child[fpp]; !present {
v := new(vector.IntVector)
child[fpp] = v
}
child[fpp].Push(fp) // Save the child PIDs on a vector
}
schild := make([]int, len(child))
i := 0
for k, _ := range child {
schild[i] = k
i++
}
sort.Ints(schild)
for _, ppid := range schild { // Walk through the sorted list
fmt.Printf("Pid %d has %d child", ppid, child[ppid].Len())
if child[ppid].Len() == 1 {
fmt.Printf(": %v\n", []int(*child[ppid]))
} else {
fmt.Printf("ren: %v\n", []int(*child[ppid]))
}
}
}
示例11: init
// Refresh the cache every hour or so.
func init() {
go func() {
for {
albumsFilename := "data/picasa/albums.json"
jsonutil.DecodeFromFile(albumsFilename, &cachedAlbums)
for _, album := range cachedAlbums {
fmt.Println("album Link: ", album.Link, ", album ID: ", album.AlbumId)
photosFilename := "data/picasa/albums/" + album.Link + ".json"
var photos []Photo
jsonutil.DecodeFromFile(photosFilename, &photos)
cachedPhotos[album.Link] = photos
}
// Note, when setting this, that updating the feed
// Causes lots of things to be swapped out in
// Low-memory enviroments. Choose a balance.
time.Sleep(1000e9) // 1000 seconds.
// Why, you may ask, is this down here? Well, because i don't want to have to wait for all of the photos to load each time i start the module for debugging.
updater := exec.Command("bin/picasa-updater")
err := updater.Run()
if err != nil {
fmt.Println("Error running photos updater:", err)
continue
}
updater.Wait()
}
}()
}
示例12: TestDump
func TestDump(t *testing.T) {
// empty
// func ParseFile(filename string, src interface{}, scope *ast.Scope, mode uint) (*ast.File, os.Error)
/*
file, e := parser.ParseFile(nil, "dump_test.go", nil, parser.ParseComments)
if e != nil {
fmt.Println("error", e)
} else {
*/
// fmt.Printf("%#v\n", file);
// Dump(file)
Dump(map[string]int{"satu": 1, "dua": 2})
Dump([]int{1, 2, 3})
Dump([3]int{1, 2, 3})
Dump(&[][]int{[]int{1, 2, 3}, []int{1, 2, 3}, []int{1, 2, 3}})
Dump(&emptyString)
Dump(T{S{1, 2}, 3})
Dump(token.STRING)
bulet := make([]Circular, 3)
bulet[0].c = &bulet[1]
bulet[1].c = &bulet[2]
bulet[2].c = &bulet[0]
Dump(struct{ a []Circular }{bulet})
cmd := exec.Command("ls", "-la")
Dump(cmd)
// }
}
示例13: run
// run executes the specified command and returns its output and an error.
func run(args ...string) ([]byte, os.Error) {
var buf bytes.Buffer
cmd := exec.Command(args[0], args[1:]...)
cmd.Stdout = &buf
cmd.Stderr = cmd.Stdout
// Start command and leave in 'running'.
running.Lock()
if running.cmd != nil {
defer running.Unlock()
return nil, fmt.Errorf("already running %s", running.cmd.Path)
}
if err := cmd.Start(); err != nil {
running.Unlock()
return nil, err
}
running.cmd = cmd
running.Unlock()
// Wait for the command. Clean up,
err := cmd.Wait()
running.Lock()
if running.cmd == cmd {
running.cmd = nil
}
running.Unlock()
return buf.Bytes(), err
}
示例14: runTest
func runTest(toolchain, test string) (stderr string, err os.Error) {
cmd := exec.Command(path.Join(toolchain, "bin/llc"), "-O0", "-stats", "--time-passes",
"-relocation-model=pic", "-O0", "-asm-verbose=false")
var data []byte
if data, err = ioutil.ReadFile(test); err != nil {
return
}
cmd.Stdin = bytes.NewBuffer(data)
var outPipe, errPipe io.Reader
if errPipe, err = cmd.StderrPipe(); err != nil {
return
}
if outPipe, err = cmd.StdoutPipe(); err != nil {
return
}
if err = cmd.Start(); err != nil {
return "", fmt.Errorf("cmd.Start: %v", err)
}
if _, err = ioutil.ReadAll(outPipe); err != nil {
return "", fmt.Errorf("ioutil.ReadAll(outPipe): %v", err)
}
var stderrData []byte
if stderrData, err = ioutil.ReadAll(errPipe); err != nil {
return "", fmt.Errorf("ioutil.ReadAll(errPipe): %v", err)
}
if err = cmd.Wait(); err != nil {
return "", fmt.Errorf("cmd.Wait: %v", err)
}
stderr = string(stderrData)
return
}
示例15: diff
func diff(b1, b2 []byte) (data []byte, err os.Error) {
f1, err := ioutil.TempFile("", "gofmt")
if err != nil {
return
}
defer os.Remove(f1.Name())
defer f1.Close()
f2, err := ioutil.TempFile("", "gofmt")
if err != nil {
return
}
defer os.Remove(f2.Name())
defer f2.Close()
f1.Write(b1)
f2.Write(b2)
data, err = exec.Command("diff", "-u", f1.Name(), f2.Name()).CombinedOutput()
if len(data) > 0 {
// diff exits with a non-zero status when the files don't match.
// Ignore that failure as long as we get output.
err = nil
}
return
}