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

Golang exec.LookPath函数代码示例

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

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



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

示例1: Compile

// Compile compiles and links sourcefile and atomically renames the
// resulting binary to runfile.
func Compile(sourcefile, runfile string, useGd bool) (err os.Error) {

	pid := strconv.Itoa(os.Getpid())

	content, err := ioutil.ReadFile(sourcefile)
	if len(content) > 2 && content[0] == '#' && content[1] == '!' {
		content[0] = '/'
		content[1] = '/'
		sourcefile = runfile + "." + pid + ".go"
		ioutil.WriteFile(sourcefile, content, 0600)
		defer os.Remove(sourcefile)
	}

	bindir := filepath.Join(runtime.GOROOT(), "bin")
	if useGd {
		gd := filepath.Join(bindir, "mgd")
		if _, err := os.Stat(gd); err != nil {
			if gd, err = exec.LookPath("mgd"); err != nil {
				return os.NewError("can't find mgd")
			}
		}
		err = Exec([]string{gd, "-L", "_obj", ".", "-q", "-o", runfile})
		return err
	} else {
		n := TheChar()
		gc := filepath.Join(bindir, n+"g")
		ld := filepath.Join(bindir, n+"l")
		if _, err := os.Stat(gc); err != nil {
			if gc, err = exec.LookPath(n + "g"); err != nil {
				return os.NewError("can't find " + n + "g")
			}
		}
		if _, err := os.Stat(ld); err != nil {
			if ld, err = exec.LookPath(n + "l"); err != nil {
				return os.NewError("can't find " + n + "l")
			}
		}
		gcout := runfile + "." + pid + "." + n
		ldout := runfile + "." + pid
		err = Exec([]string{gc, "-o", gcout, sourcefile})
		if err != nil {
			return err
		}
		defer os.Remove(gcout)
		err = Exec([]string{ld, "-o", ldout, gcout})
		if err != nil {
			return err
		}
		return os.Rename(ldout, runfile)
	}
	panic("Unreachable code")
}
开发者ID:ssrl,项目名称:gonrun,代码行数:54,代码来源:gonrun.go


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


示例3: envOrDefault

func envOrDefault(cmd, dfl string) string {
	p, err := exec.LookPath(cmd)
	if err != nil {
		return dfl
	}
	return p
}
开发者ID:andradeandrey,项目名称:Faff,代码行数:7,代码来源:main.go


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


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


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


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


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


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


示例10: TestRmRf

func TestRmRf(t *testing.T) {
	t.Log("TestRmRf")
	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)
	bin, err := exec.LookPath("rm")
	CheckSuccess(err)
	cmd := exec.Command(bin, "-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:CloudLife,项目名称:go-fuse,代码行数:32,代码来源:unionfs_test.go


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


示例12: getProgramPath

func getProgramPath() (string, os.Error) {
	program := os.Args[0]
	dir, _ := path.Split(program)

	if dir == "" {
		binPath, pathError := exec.LookPath(program)

		if pathError != nil {
			if syscall.Access(program, syscall.O_RDONLY) != 0 {
				return "", os.NewError("Path to " + program + " couldn't be found")
			}

			cwd, cwdError := os.Getwd()

			if cwdError != nil {
				return "", cwdError
			}

			return cwd, nil
		}

		binPath, _ = path.Split(binPath)
		return binPath, nil
	}

	dir, _ = abspath(dir)
	return dir, nil
}
开发者ID:essiene,项目名称:efene,代码行数:28,代码来源:fnc.go


示例13: main

func main() {
	commands := []string{
		`ls /home`,
		`ls '/home'`,
		`ls -l /home`,
		`echo 'Hello, one and all!'`,
		`which python`,

		// Outputs "hello, world\n" instead of "\n"
		`python -c print 'hello, world'`,

		// Outputs "\n" instead of "hello, world\n"
		`python -c "print 'hello, world'"`,
	}

	for ndx, c := range commands {
		fmt.Printf("Command %d of %d:  %s\n", ndx+1, len(commands), c)

		// When I replace 3 with -1, the last 2 commands produce a Python error
		argv := strings.Split(c, " ", 3)

		bin, err := exec.LookPath(argv[0])
		if cmd, e := exec.Run(bin, argv, nil, "", exec.DevNull, exec.Pipe, exec.MergeWithStdout); e == nil && err == nil {
			body, _ := ioutil.ReadAll(cmd.Stdout)
			fmt.Printf("%s\n", string(body))
		} else {
			fmt.Printf("e: %v", e)
			fmt.Printf("err: %v", err)
		}
	}
}
开发者ID:sbhackerspace,项目名称:sbhx-snippets,代码行数:31,代码来源:system-output-bugreport.go


示例14: CreateTestArgv

func CreateTestArgv() []string {

	pwd, e := os.Getwd()

	if e != nil {
		log.Fatal("[ERROR] could not locate working directory\n")
	}

	argv := make([]string, 0)

	if global.GetString("-backend") == "express" {
		vmrun, e := exec.LookPath("vmrun")
		if e != nil {
			log.Fatalf("[ERROR] %s\n", e)
		}
		argv = append(argv, vmrun)
	}

	argv = append(argv, filepath.Join(pwd, global.GetString("-test-bin")))

	if global.GetString("-bench") != "" {
		argv = append(argv, "-test.bench")
		argv = append(argv, global.GetString("-bench"))
	}
	if global.GetString("-match") != "" {
		argv = append(argv, "-test.run")
		argv = append(argv, global.GetString("-match"))
	}
	if global.GetBool("-verbose") {
		argv = append(argv, "-test.v")
	}
	return argv
}
开发者ID:ssrl,项目名称:mgd,代码行数:33,代码来源:compiler.go


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


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


示例17: init

func init() {
	cache := make(map[string]string)
	translations := make(map[string]string)
	for i := '1'; i < '7'; i++ {
		for sv := 0; sv <= bridge.NoTrump; sv++ {
			stringi := string([]byte{byte(i)})
			spoken := stringi + " " + bridge.SuitName[sv] + "."
			translations[stringi+bridge.SuitHTML[sv]] = spoken
			translations[stringi+bridge.SuitLetter[sv]] = spoken
			translations[stringi+bridge.SuitColorHTML[sv]] = spoken
		}
	}
	translations[" P"] = "Pass."
	translations["P"] = "Pass."
	translations[" X"] = "Double!"
	translations["X"] = "Double!"
	translations["XX"] = "Redouble!"
	espeak, err := exec.LookPath("espeak")
	if err == nil {
		go func() {
			for {
				req := <-seek_speech
				bid := req.bid
				if sp, ok := translations[bid]; ok {
					bid = sp
				}
				fmt.Println("I am speaking:", bid)
				if s, ok := cache[req.bid]; ok {
					req.answer <- answertype{s, nil}
				} else {
					c, err := exec.Run(espeak, []string{"espeak", "--stdout"}, nil, "",
						exec.Pipe, exec.Pipe, exec.PassThrough)
					if err != nil {
						req.answer <- answertype{"", err}
						continue
					}
					defer c.Close()
					fmt.Fprintln(c.Stdin, bid)
					c.Stdin.Close()
					o, err := ioutil.ReadAll(c.Stdout)
					if err != nil {
						req.answer <- answertype{"", err}
						continue
					}
					out := string(o)
					cache[req.bid] = out
					req.answer <- answertype{out, nil}
				}
			}
		}()
	} else {
		go func() {
			fmt.Println("We won't be able to speak, since I can't find espeak!", err)
			for {
				req := <-seek_speech
				req.answer <- answertype{"", os.NewError("Cannot find espeak in path.")}
			}
		}()
	}
}
开发者ID:droundy,项目名称:abridge,代码行数:60,代码来源:speech.go


示例18: GetPath

func GetPath() string {
	file, _ := exec.LookPath(os.Args[0])
	dir, _ := path.Split(file)
	os.Chdir(dir)
	path, _ := os.Getwd()
	return path + "/"
}
开发者ID:WaylandGod,项目名称:Go2D,代码行数:7,代码来源:tools.go


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


示例20: run

func run(argv []string) os.Error {
	cmd, err := exec.LookPath(argv[0])
	if err != nil {
		return err
	}
	var stdin *os.File
	if syscall.OS == "windows" {
		stdin, _ = os.Open("CONIN$")
	} else {
		stdin = os.Stdin
	}
	p, err := os.StartProcess(cmd, argv, &os.ProcAttr{Files: []*os.File{stdin, os.Stdout, os.Stderr}})
	if err != nil {
		return err
	}
	defer p.Release()
	w, err := p.Wait(0)
	if err != nil {
		return err
	}
	if !w.Exited() || w.ExitStatus() != 0 {
		return os.NewError("failed to execute text editor")
	}
	return nil
}
开发者ID:andradeandrey,项目名称:goissue,代码行数:25,代码来源:main.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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