• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang exec.Command函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中exec.Command函数的典型用法代码示例。如果您正苦于以下问题:Golang Command函数的具体用法?Golang Command怎么用?Golang Command使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Command函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
}
开发者ID:wb253,项目名称:go-gb,代码行数:29,代码来源:runext.go


示例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)
	}
}
开发者ID:khronnuz,项目名称:manga-processor,代码行数:55,代码来源:Main.go


示例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()
	}
}
开发者ID:Altece,项目名称:Go-Go-Gadget-Repo,代码行数:18,代码来源:screen.go


示例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()
}
开发者ID:ipeet,项目名称:camlistore,代码行数:11,代码来源:openurl.go


示例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)
}
开发者ID:CloudLife,项目名称:go-fuse,代码行数:53,代码来源:stat_test.go


示例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
}
开发者ID:aubonbeurre,项目名称:gcc,代码行数:29,代码来源:build.go


示例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
}
开发者ID:wb253,项目名称:go-gb,代码行数:25,代码来源:runext.go


示例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
}
开发者ID:jnwhiteh,项目名称:go,代码行数:30,代码来源:main.go


示例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)
	}
}
开发者ID:klimek,项目名称:go-fuse,代码行数:31,代码来源:unionfs_test.go


示例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]))
		}
	}
}
开发者ID:raphaeldore,项目名称:gobook,代码行数:33,代码来源:proc.go


示例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()
		}
	}()
}
开发者ID:Epictetus,项目名称:wfdr,代码行数:31,代码来源:picasa.go


示例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)
	//	}
}
开发者ID:ZyberM,项目名称:dump.go,代码行数:30,代码来源:dump_test.go


示例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
}
开发者ID:k001,项目名称:Golang-spanish-documentation,代码行数:29,代码来源:local.go


示例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
}
开发者ID:krasin,项目名称:llvm-side-by-side,代码行数:32,代码来源:main.go


示例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

}
开发者ID:WXB506,项目名称:golang,代码行数:27,代码来源:gofmt.go


示例16: runLog

// runLog runs a process and returns the combined stdout/stderr,
// as well as writing it to logfile (if specified). It returns
// process combined stdout and stderr output, exit status and error.
// The error returned is nil, if process is started successfully,
// even if exit status is not 0.
func runLog(envv []string, logfile, dir string, argv ...string) (string, int, os.Error) {
	if *verbose {
		log.Println("runLog", argv)
	}
	argv = useBash(argv)

	b := new(bytes.Buffer)
	var w io.Writer = b
	if logfile != "" {
		f, err := os.OpenFile(logfile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
		if err != nil {
			return "", 0, err
		}
		defer f.Close()
		w = io.MultiWriter(f, b)
	}

	cmd := exec.Command(argv[0], argv[1:]...)
	cmd.Dir = dir
	cmd.Env = envv
	cmd.Stdout = w
	cmd.Stderr = w

	err := cmd.Run()
	if err != nil {
		if ws, ok := err.(*os.Waitmsg); ok {
			return b.String(), ws.ExitStatus(), nil
		}
	}
	return b.String(), 0, nil
}
开发者ID:WXB506,项目名称:golang,代码行数:36,代码来源:exec.go


示例17: updateRepo

// updateRepo gets a list of tags in the repository and
// checks out the tag closest to the current runtime.Version.
// If no matching tag is found, it just updates to tip.
func (v *vcs) updateRepo(dst string) os.Error {
	if v.tagList == "" || v.tagListRe == nil {
		// TODO(adg): fix for svn
		return run(dst, nil, v.cmd, v.update)
	}

	// Get tag list.
	stderr := new(bytes.Buffer)
	cmd := exec.Command(v.cmd, v.tagList)
	cmd.Dir = dst
	cmd.Stderr = stderr
	b, err := cmd.Output()
	if err != nil {
		errorf("%s %s: %s\n", v.cmd, v.tagList, stderr)
		return err
	}
	var tags []string
	for _, m := range v.tagListRe.FindAllStringSubmatch(string(b), -1) {
		tags = append(tags, m[1])
	}

	// Only use the tag component of runtime.Version.
	ver := strings.Split(runtime.Version(), " ")[0]

	// Select tag.
	if tag := selectTag(ver, tags); tag != "" {
		printf("selecting revision %q\n", tag)
		return run(dst, nil, v.cmd, v.checkout, v.updateRevFlag+tag)
	}

	// No matching tag found, make default selection.
	printf("selecting tip\n")
	return run(dst, nil, v.cmd, v.update)
}
开发者ID:vablaya,项目名称:gopp-cs345,代码行数:37,代码来源:download.go


示例18: backupCopy

func backupCopy(dir string) {
	_, err := exec.Command("cp", "-r", dir, dir+"__").Output()
	if err != nil {
		fmt.Println("falha ao criar backup " + err.String())
		panic(err.String())
	}
}
开发者ID:khronnuz,项目名称:manga-processor,代码行数:7,代码来源:Main.go


示例19: StdExecve

func StdExecve(argv []string, stopOnTrouble bool) bool {

	var err os.Error
	var cmd *exec.Cmd

	switch len(argv) {
	case 0:
		if stopOnTrouble {
			log.Fatalf("[ERROR] len(argv) == 0\n")
		}
		return false
	case 1:
		cmd = exec.Command(argv[0])
	default:
		cmd = exec.Command(argv[0], argv[1:]...)
	}

	// pass-through
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.Stdin = os.Stdin

	err = cmd.Start()

	if err != nil {
		if stopOnTrouble {
			log.Fatalf("[ERROR] %s\n", err)
		} else {
			log.Printf("[ERROR] %s\n", err)
			return false
		}
	}

	err = cmd.Wait()

	if err != nil {
		if stopOnTrouble {
			log.Fatalf("[ERROR] %s\n", err)
		} else {
			log.Printf("[ERROR] %s\n", err)
			return false
		}
	}

	return true
}
开发者ID:ssrl,项目名称:mgd,代码行数:46,代码来源:handy.go


示例20: run

func run(command string) os.Error {
	output, err := exec.Command("/bin/sh", "-c", command).CombinedOutput()
	if err != nil {
		msg := fmt.Sprintf("Failed to execute: %s: %s\n%s", command, err.String(), string(output))
		return os.NewError(msg)
	}
	return nil
}
开发者ID:adamsxu,项目名称:mgo,代码行数:8,代码来源:suite_test.go



注:本文中的exec.Command函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang exec.LookPath函数代码示例发布时间:2022-05-24
下一篇:
Golang event.Event类代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap