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

Golang exec.Run函数代码示例

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

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



在下文中一共展示了Run函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: 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
	}
	// fmt.Fprintf(os.Stderr, "%v\n", argv);
	var cmd *exec.Cmd
	if len(input) == 0 {
		cmd, err = exec.Run(prog, argv, os.Environ(), "", exec.DevNull, exec.Pipe, exec.MergeWithStdout)
		if err != nil {
			goto Error
		}
	} else {
		cmd, err = exec.Run(prog, argv, os.Environ(), "", exec.Pipe, exec.Pipe, exec.MergeWithStdout)
		if err != nil {
			goto Error
		}
		go func() {
			cmd.Stdin.Write(input)
			cmd.Stdin.Close()
		}()
	}
	defer cmd.Close()
	var buf bytes.Buffer
	_, err = io.Copy(&buf, cmd.Stdout)
	out = buf.String()
	if err != nil {
		cmd.Wait(0)
		goto Error
	}
	w, err := cmd.Wait(0)
	if err != nil {
		goto Error
	}
	if !w.Exited() || w.ExitStatus() != 0 {
		err = w
		goto Error
	}
	return

Error:
	err = &runError{copy(argv), err}
	return
}
开发者ID:ivanwyc,项目名称:google-go,代码行数:54,代码来源:main.go


示例2: main

func main() {
	ts, e := os.Open("tests", os.O_RDONLY, 0)
	error.FailOn(e)
	error.FailOn(os.RemoveAll("tests/tmp"))
	ds, e := ts.Readdir(-1)
	error.FailOn(e)
	// Set up an environment with an appropriate path
	wd, e := os.Getwd()
	error.FailOn(e)
	os.Setenv("PATH", path.Join(wd, "bin")+":"+os.Getenv("PATH"))
	for _, d := range ds {
		if d.IsRegular() && (d.Permission()&1) == 1 && endsWith(d.Name, ".sh") {
			basename := d.Name[0 : len(d.Name)-3]
			fmt.Printf("Running %s... ", basename)
			dirname := path.Join("tests/tmp", basename)
			error.FailOn(os.MkdirAll(dirname, 0777))
			pid, e := exec.Run(path.Join(wd, "tests", d.Name), []string{}, os.Environ(), dirname,
				exec.DevNull, exec.Pipe, exec.MergeWithStdout)
			error.FailOn(e)
			o, e := ioutil.ReadAll(pid.Stdout)
			error.FailOn(e)
			ret, e := pid.Wait(0)
			error.FailOn(e)
			if ret.ExitStatus() != 0 {
				error.Print("FAILED!\n", string(o))
				error.Print("Test '", basename, "' failed!")
				exit.Exit(1)
			}
			fmt.Println("passed.")
		}
	}
}
开发者ID:droundy,项目名称:iolaus,代码行数:32,代码来源:harness.go


示例3: runShellCommand

func runShellCommand(argv []string) map[string]string {
	result := map[string]string{
		"out": "",
		"err": ""}

	app := argv[0]
	home := fmt.Sprintf("HOME=%v", os.Getenv("HOME"))
	path := fmt.Sprintf("PATH=%v", os.Getenv("PATH"))
	env := []string{home, path}

	cmd, err := exec.Run(app, argv, env, "", exec.DevNull, exec.Pipe, exec.Pipe)

	if err != nil {
		fmt.Fprintln(os.Stderr, err.String())
		result["err"] = err.String()
		return result
	}

	var b1 bytes.Buffer
	io.Copy(&b1, cmd.Stdout)
	fmt.Println(b1.String())
	result["out"] = b1.String()

	var b2 bytes.Buffer
	io.Copy(&b2, cmd.Stderr)
	fmt.Println(b2.String())
	result["err"] = b2.String()

	cmd.Close()

	return result
}
开发者ID:nicneo925,项目名称:appscale,代码行数:32,代码来源:neptune.go


示例4: justrun

func justrun(cmd string, args ...string) os.Error {
	abscmd, err := exec.LookPath(cmd)
	if err != nil {
		return os.NewError("Couldn't find " + cmd + ": " + err.String())
	}

	cmdargs := make([]string, len(args)+1)
	cmdargs[0] = cmd
	for i, a := range args {
		cmdargs[i+1] = a
	}
	pid, err := exec.Run(abscmd, cmdargs, nil, "",
		exec.PassThrough, exec.PassThrough, exec.PassThrough)
	if err != nil {
		return err
	}
	wmsg, err := pid.Wait(0)
	if err != nil {
		return err
	}
	if wmsg.ExitStatus() != 0 {
		return os.NewError(cmd + " exited with status " + fmt.Sprint(wmsg.ExitStatus()))
	}
	return nil
}
开发者ID:droundy,项目名称:go-crazy,代码行数:25,代码来源:go-crazy.go


示例5: Stop

func (p *ProcessStarter) Stop(com *Command, reply *string) os.Error {
	fmt.Printf("try stopping process\n")
	data, ok := processMap[com.name]
	if !ok {
		fmt.Printf("server unknown:%s", com.name)
	} else {
		if data.cmd != nil && data.cmd.Pid > 0 {
			fmt.Printf("kill pid server %d:", data.cmd.Pid)
			var pid string = fmt.Sprintf("%d", data.cmd.Pid)
			println(pid)
			args := []string{com.command, "--stop", pid}
			env := []string{"DYLD_LIBRARY_PATH=/Users/jholscher/Documents/bripper/install/lib/"}
			_, err := exec.Run(com.command, args, env, com.dir, exec.DevNull, exec.Pipe, exec.PassThrough)
			if err != nil {
				fmt.Println("error stop process")
			} else {
				//fmt.Println("process stopped")
			}

			//		syscall.Kill(data.cmd.Pid, 15)
		} else {
			fmt.Printf("failed to stop the process, because one of the following data is nil or lower 0 [%s,%d]", data.cmd, data.cmd.Pid)
		}
	}

	return nil
}
开发者ID:psychobob666,项目名称:MediaEncodingCluster,代码行数:27,代码来源:mainrpc.go


示例6: mustRunDoozer

func mustRunDoozer(listen, web, attach string) *exec.Cmd {
	exe, err := exec.LookPath("doozerd")
	if err != nil {
		panic(err)
	}

	args := []string{
		"doozerd",
		"-l=127.0.0.1:" + listen,
		"-w=127.0.0.1:" + web,
	}

	if attach != "" {
		args = append(args, "-a", "127.0.0.1:"+attach)
	}

	cmd, err := exec.Run(
		exe,
		args,
		nil,
		".",
		exec.PassThrough,
		exec.PassThrough,
		exec.PassThrough,
	)
	if err != nil {
		panic(err)
	}

	return cmd
}
开发者ID:kr,项目名称:doozer,代码行数:31,代码来源:fail_test.go


示例7: ExecRead

func ExecRead(cmd string, args ...string) (out []byte, err os.Error) {
	abscmd, err := exec.LookPath(cmd)
	if err != nil {
		return out, os.NewError("Couldn't find " + cmd + ": " + err.String())
	}

	cmdargs := make([]string, len(args)+1)
	cmdargs[0] = cmd
	for i, a := range args {
		cmdargs[i+1] = a
	}
	printexec(cmd, args)

	pid, err := exec.Run(abscmd, cmdargs, nil, "",
		exec.PassThrough, exec.Pipe, exec.PassThrough)
	if err != nil {
		return
	}
	out, err = ioutil.ReadAll(pid.Stdout)
	if err != nil {
		return
	}
	ws, err := pid.Wait(0) // could have been os.WRUSAGE
	if err != nil {
		return
	}
	if ws.ExitStatus() != 0 {
		err = os.NewError(cmd + " exited with status " + strconv.Itoa(ws.ExitStatus()))
	}
	return out, nil
}
开发者ID:andradeandrey,项目名称:goadmin,代码行数:31,代码来源:deps.go


示例8: main

func main() {
	flag.Parse()
	cwd, _ := os.Getwd()
	binary, _ := exec.LookPath(flag.Args()[0])
	for {
		cmd, _ := exec.Run(binary, flag.Args(), nil, cwd, exec.PassThrough, exec.PassThrough, exec.PassThrough)
		pid := cmd.Process.Pid
		extras := make(ABC, 0)

		if *httpTimeoutUrl != "" {
			extras = append(extras, setupHttpTimeoutCheck(pid))
		}

		if *httpStatusUrl != "" {
			extras = append(extras, setupHttpStatusCheck(pid))
		}

		if *maxMemory > 0 {
			extras = append(extras, setupMaxMemoryCheck(pid))
		}

		cmd.Wait(os.WSTOPPED)
		println("Process died, restarting.")
		extras.closeAll()
	}
}
开发者ID:darkhelmet,项目名称:sniper,代码行数:26,代码来源:scout-sniper.go


示例9: diff

func diff(b1, b2 []byte) (data []byte, err os.Error) {
	f1, err := ioutil.TempFile("", "gofix")
	if err != nil {
		return nil, err
	}
	defer os.Remove(f1.Name())
	defer f1.Close()

	f2, err := ioutil.TempFile("", "gofix")
	if err != nil {
		return nil, err
	}
	defer os.Remove(f2.Name())
	defer f2.Close()

	f1.Write(b1)
	f2.Write(b2)

	diffcmd, err := exec.LookPath("diff")
	if err != nil {
		return nil, err
	}

	c, err := exec.Run(diffcmd, []string{"diff", f1.Name(), f2.Name()}, nil, "",
		exec.DevNull, exec.Pipe, exec.MergeWithStdout)
	if err != nil {
		return nil, err
	}
	defer c.Close()

	return ioutil.ReadAll(c.Stdout)
}
开发者ID:go-nosql,项目名称:golang,代码行数:32,代码来源:main.go


示例10: Build

// Build runs makepkg on the specified srcdir. A slice of package paths are
// returned. These are the paths to the binary packages that are built. Packages
// with multiple pkgnames build multiple packages, hence the use of a slice.
// If an error occurs, returns nil and the error.
//
// Notice that we do not actually set PKGDEST ourselves, this should be done
// before calling this function. Otherwise the built package will just end up
// in the package source directory. Maybe.
func (builder *PackageBuilder) Build(srcdir string) ([]string, os.Error) {
	// Create a tempfile and hook it into our bash tomfoolery.
	pathfile, err := NewPkgPathFile()
	if err != nil {
		return nil, err
	}
	defer pathfile.Cleanup()

	// Call our included utility, mawmakepkg which wraps makepkg to drop priveledges
	// and print the paths of built packages to our tempfile.
	args := []string{MawMakepkgPath, pathfile.Name(), "-s", "-m", "-f"}
	cmd, err := exec.Run(MawMakepkgPath, args, nil, srcdir,
		exec.PassThrough, exec.PassThrough, exec.PassThrough)
	if err != nil {
		return nil, err
	}
	defer cmd.Process.Release()

	waitmsg, err := cmd.Wait(0)
	if code := waitmsg.ExitStatus(); code != 0 {
		return nil, os.NewError("makepkg failed")
	}

	return pathfile.ReadLines()
}
开发者ID:juster,项目名称:maw,代码行数:33,代码来源:srcpkg.go


示例11: genRun

// genRun implements run and tryRun.
func genRun(dir string, stdin []byte, cmd []string, quiet bool) os.Error {
	bin, err := exec.LookPath(cmd[0])
	if err != nil {
		return err
	}
	p, err := exec.Run(bin, cmd, os.Environ(), dir, exec.Pipe, exec.Pipe, exec.MergeWithStdout)
	if *verbose {
		fmt.Fprintf(os.Stderr, "%s: %s; %s %s\n", argv0, dir, bin, strings.Join(cmd[1:], " "))
	}
	if err != nil {
		return err
	}
	go func() {
		p.Stdin.Write(stdin)
		p.Stdin.Close()
	}()
	var buf bytes.Buffer
	io.Copy(&buf, p.Stdout)
	io.Copy(&buf, p.Stdout)
	w, err := p.Wait(0)
	p.Close()
	if !w.Exited() || w.ExitStatus() != 0 {
		if !quiet || *verbose {
			if dir != "" {
				dir = "cd " + dir + "; "
			}
			fmt.Fprintf(os.Stderr, "%s: === %s%s\n", argv0, dir, strings.Join(cmd, " "))
			os.Stderr.Write(buf.Bytes())
			fmt.Fprintf(os.Stderr, "--- %s\n", w)
		}
		return os.ErrorString("running " + cmd[0] + ": " + w.String())
	}
	return nil
}
开发者ID:ivanwyc,项目名称:google-go,代码行数:35,代码来源:main.go


示例12: build

func build(gcfile string, opts []string, proFileName string, files []string, envv []string, dir string) (status syscall.WaitStatus, err os.Error) {
	arg := []string{gcfile, "-o", proFileName}
	for _, v := range opts {
		arg = append(arg, v)
	}
	for _, v := range files {
		arg = append(arg, string(v))
	}
	fmt.Println("\t", arg)
	var cmd *exec.Cmd
	cmd, err = exec.Run(gcfile, arg[:], envv[:], dir, 0, 1, 2)
	if err != nil {
		fmt.Printf("Error, %s", err)
		return
	}
	defer cmd.Close()
	var wait *os.Waitmsg
	wait, err = cmd.Wait(0)
	if err != nil {
		fmt.Printf("Error, %s", err)
		return
	}
	status = wait.WaitStatus
	return
}
开发者ID:gaopeng1106,项目名称:liteide.liteide,代码行数:25,代码来源:promake.go


示例13: run

// run executes the specified command and returns its output and an error.
func run(cmd ...string) ([]byte, os.Error) {
	// find the specified binary
	bin, err := exec.LookPath(cmd[0])
	if err != nil {
		// report binary as well as the error
		return nil, os.NewError(cmd[0] + ": " + err.String())
	}

	// run the binary and read its combined stdout and stderr into a buffer
	p, err := exec.Run(bin, cmd, os.Environ(), "", exec.DevNull, exec.Pipe, exec.MergeWithStdout)
	if err != nil {
		return nil, err
	}
	var buf bytes.Buffer
	io.Copy(&buf, p.Stdout)
	w, err := p.Wait(0)
	p.Close()
	if err != nil {
		return nil, err
	}

	// set the error return value if the program had a non-zero exit status
	if !w.Exited() || w.ExitStatus() != 0 {
		err = os.ErrorString("running " + cmd[0] + ": " + w.String())
	}

	return buf.Bytes(), err
}
开发者ID:go-nosql,项目名称:golang,代码行数:29,代码来源:goplay.go


示例14: Run

func Run(prog, dir string, argv []string) ([]string, os.Error) {
	cmd, err := exec.Run(prog, argv, nil, dir, exec.Pipe, exec.Pipe, exec.Pipe)
	if err != nil {
		if cmd != nil {
			cmd.Close()
		}
		return []string{""}, err
	}
	liner, err := bufio.NewReaderSize(cmd.Stdout, 2000)
	if err != nil {
		cmd.Close()
		return nil, err
	}
	r := []string{}
	var l []byte
	for {
		l, _, err = liner.ReadLine()
		if err != nil {
			break
		}
		r = append(r, string(l))
	}
	if err != nil && err != os.EOF {
		cmd.Close()
		return nil, err
	}
	err = cmd.Close()
	return r, err
}
开发者ID:andradeandrey,项目名称:Faff,代码行数:29,代码来源:git.go


示例15: RunExternalDump

func RunExternalDump(cmd, wd string, argv []string, dump io.Writer) (err os.Error) {
	var p *exec.Cmd
	p, err = exec.Run(cmd, argv, nil, wd, exec.PassThrough, exec.Pipe, exec.PassThrough)
	if err != nil {
		return
	}
	if p != nil {
		src := p.Stdout
		buffer := make([]byte, 1024)
		for {
			n, cpErr := src.Read(buffer)
			if cpErr != nil {
				break
			}
			_, cpErr = dump.Write(buffer[0:n])
			if cpErr != nil {
				break
			}
		}

		var wmsg *os.Waitmsg
		wmsg, err = p.Wait(0)
		if wmsg.ExitStatus() != 0 {
			err = os.NewError(fmt.Sprintf("%v: %s\n", argv, wmsg.String()))
			return
		}
		if err != nil {
			return
		}
	}
	return
}
开发者ID:clarencethecat,项目名称:gbide,代码行数:32,代码来源:gbrun.go


示例16: Format

// Format takes a markdown-formatted string and returns an equivalent
// HTML-formatted string.
//
// TODO write built-in markdown implementation, to avoid forking for every
// post
func Format(md string) (html string, err os.Error) {
	cmdName, err := exec.LookPath("markdown")
	if err != nil {
		return
	}
	cmd, err := exec.Run(
		cmdName,
		[]string{},
		os.Environ(),
		".",
		exec.Pipe,
		exec.Pipe,
		exec.PassThrough,
	)
	if err != nil {
		return
	}
	cmd.Stdin.WriteString(md)
	cmd.Stdin.Close()
	b, err := ioutil.ReadAll(cmd.Stdout)
	if err != nil {
		return
	}
	html = string(b)
	err = cmd.Close()
	return
}
开发者ID:bytbox,项目名称:obsidian,代码行数:32,代码来源:markdown.go


示例17: WriteReadS

func WriteReadS(arg1 string, inp string, args []string) (output string, e os.Error) {
	debug.Println("calling git",arg1,args)
	args = stringslice.Cat([]string{"git", arg1}, args)
	output = "" // empty output if we have an error...
	git, e := exec.LookPath("git")
	if e != nil { e = explain("exec.LookPath",e); return }
	pid,e := exec.Run(git, args, os.Environ(), ".",
		exec.Pipe, exec.Pipe, exec.PassThrough)
	if e != nil { announce(e); return }
	_,e = fmt.Fprint(pid.Stdin, inp)
	if e != nil { announce(e); return }
	e = pid.Stdin.Close()
	if e != nil { announce(e); return }
	o,e := ioutil.ReadAll(pid.Stdout)
	output = string(o)
	if e != nil { announce(e); return }
	ws,e := pid.Wait(0) // could have been os.WRUSAGE
	if e != nil { announce(e); return }
	if ws.ExitStatus() != 0 {
		e = os.NewError(fmt.Sprintf("git exited with '%v'",ws.ExitStatus()))
		announce(e)
		return
	}
	return
}
开发者ID:droundy,项目名称:iolaus,代码行数:25,代码来源:git.go


示例18: clean

/*
 This function does exactly the same as "make clean".
*/
func clean() {
	bashBin, err := exec.LookPath("bash")
	if err != nil {
		logger.Error("Need bash to clean.\n")
		os.Exit(127)
	}

	argv := []string{bashBin, "-c", "commandhere"}

	if *flagVerboseMode {
		argv[2] = "rm -rfv *.[568]"
	} else {
		argv[2] = "rm -rf *.[568]"
	}

	logger.Info("Running: %v\n", argv[2:])

	cmd, err := exec.Run(bashBin, argv, os.Environ(), rootPath,
		exec.DevNull, exec.PassThrough, exec.PassThrough)
	if err != nil {
		logger.Error("%s\n", err)
		os.Exit(1)
	}
	waitmsg, err := cmd.Wait(0)
	if err != nil {
		logger.Error("Couldn't delete files: %s\n", err)
		os.Exit(1)
	}

	if waitmsg.ExitStatus() != 0 {
		logger.Error("rm returned with errors.\n")
		os.Exit(waitmsg.ExitStatus())
	}
}
开发者ID:ShadowIce,项目名称:gobuild,代码行数:37,代码来源:gobuild.go


示例19: run

func run(name string, args ...string) string {
	path, err := exec.LookPath(name)
	if err != nil {
		panic(err)
	}

	cwd, err := os.Getwd()
	if err != nil {
		panic(err)
	}

	p, err := exec.Run(path, append([]string{name}, args...), os.Environ(),
		cwd, exec.Pipe, exec.Pipe, exec.Pipe)
	if err != nil {
		panic(err)
	}
	defer p.Close()

	data, err := ioutil.ReadAll(p.Stdout)
	if err != nil {
		panic(err)
	}

	return strings.TrimSpace(string(data))
}
开发者ID:nsf,项目名称:gortfm,代码行数:25,代码来源:gortfm-util.go


示例20: runWithOutput

func runWithOutput(binary string, args []string) string {
	cwd, _ := os.Getwd()
	cmd, _ := exec.Run(binary, args, nil, cwd, exec.PassThrough, exec.Pipe, exec.PassThrough)
	cmd.Wait(os.WSTOPPED)
	stdout, _ := ioutil.ReadAll(cmd.Stdout)
	return strings.Trim(string(stdout), " \n")
}
开发者ID:darkhelmet,项目名称:sniper,代码行数:7,代码来源:sysinfo.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang exec.Cmd类代码示例发布时间:2022-05-24
下一篇:
Golang exec.LookPath函数代码示例发布时间: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