当前位置: 首页>>代码示例>>Golang>>正文


Golang Cmd.Env方法代码示例

本文整理汇总了Golang中os/exec.Cmd.Env方法的典型用法代码示例。如果您正苦于以下问题:Golang Cmd.Env方法的具体用法?Golang Cmd.Env怎么用?Golang Cmd.Env使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在os/exec.Cmd的用法示例。


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

示例1: Start

func (lc *LocalCommand) Start() error {
	if lc.Shell == "" {
		lc.Shell = "sh"
	}

	var cmd *exec.Cmd
	if lc.ScriptMode {
		cmd = exec.Command(lc.Shell)
		cmd.Stdin = strings.NewReader(lc.CmdString)
	} else {
		cmd = exec.Command(lc.Shell, "-c", lc.CmdString)
	}

	// create the command, set the options
	if lc.WorkingDirectory != "" {
		cmd.Dir = lc.WorkingDirectory
	}
	cmd.Env = lc.Environment
	if cmd.Env == nil {
		cmd.Env = os.Environ()
	}
	cmd.Stdout = lc.Stdout
	cmd.Stderr = lc.Stderr

	// cache the command running
	lc.Cmd = cmd

	// start the command
	return cmd.Start()
}
开发者ID:tychoish,项目名称:evergreen,代码行数:30,代码来源:local_command.go

示例2: Compile

func (a *ERBAsset) Compile() (io.Reader, error) {
	data, err := a.input.Compile()
	if err != nil {
		return nil, err
	}

	a.l.Info("Compiling ERB")

	var buf bytes.Buffer
	var cmd *exec.Cmd
	if _, err := os.Stat("Gemfile"); err == nil {
		cmd = exec.Command("bundle", "exec", "ruby", a.erbRBPath)
	} else {
		cmd = exec.Command("ruby", a.erbRBPath)
	}
	cmd.Stdin = data
	cmd.Stdout = &buf
	cmd.Stderr = os.Stderr
	cmd.Env = os.Environ()
	cmd.Env = append(cmd.Env, fmt.Sprintf("CACHE_BREAKER=%s", a.cacheBreaker))
	if err := cmd.Run(); err != nil {
		return nil, err
	}
	return &buf, nil
}
开发者ID:jvatic,项目名称:asset-matrix-go,代码行数:25,代码来源:erb-asset.go

示例3: Exec

// Exec the given command in the background using the systemd
// notification protocol. This function returns once the command has
// either exited or signaled that it is ready. If the command exits
// with a non-zero status before signaling readiness, returns an
// exec.ExitError.
func Exec(cmd *exec.Cmd) error {
	l, err := listen()
	if err != nil {
		return err
	}
	defer func() { _ = l.close() }()

	if cmd.Env == nil {
		// Default the environment to the parent process's, minus any
		// existing versions of our variable.
		varPrefix := fmt.Sprintf("%s=", envName)
		for _, v := range os.Environ() {
			if !strings.HasPrefix(v, varPrefix) {
				cmd.Env = append(cmd.Env, v)
			}
		}
	}
	cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", envName, l.Path))

	if err := cmd.Start(); err != nil {
		return err
	}

	// This can leak goroutines, but we don't really care because we
	// always exit after calling this function.
	ch := make(chan error, 2)
	go func() {
		ch <- l.wait()
	}()
	go func() {
		ch <- cmd.Wait()
	}()
	return <-ch
}
开发者ID:veteranlu,项目名称:cockroach,代码行数:39,代码来源:sdnotify.go

示例4: main

func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "%s", Help)
		os.Exit(1)
	}
	flag.Parse()

	if *version {
		fmt.Printf("%s", Version)
		os.Exit(0)
	}

	if *unset != "" {
		os.Unsetenv(*unset)
	}

	cmd := new(exec.Cmd)
	cmd.Env = env

	// Check for "-" as an argument, because it means the same as "-i"
	if flag.Arg(0) == "-" {
		cmd.Env = make([]string, 0)
	}

	for i, arg := range flag.Args() {
		if strings.Index(arg, delim) > 0 {
			cmd.Env = append(cmd.Env, arg)
		} else if arg != "-" {
			if *nullEol {
				fatal.Fatalln("cannot specify --null (-0) with command")
			}

			cmd.Path = arg

			cmd.Args = append(cmd.Args, flag.Args()[i:]...)
			cmd.Stdin = os.Stdin
			cmd.Stdout = os.Stdout
			cmd.Stderr = os.Stderr

			err := execvp(cmd)
			if err != nil {
				fatal.Fatalln(err)
			}
			return
		}

		i++
	}

	eol := '\n'
	if *nullEol {
		eol = '\x00'
	}

	for _, e := range env {
		fmt.Printf("%s%c", e, eol)
	}

	return
}
开发者ID:postfix,项目名称:go-coreutils,代码行数:60,代码来源:env.go

示例5: Start

func (self *LocalCommand) Start() error {
	var cmd *exec.Cmd
	if self.ScriptMode {
		cmd = exec.Command("sh")
		cmd.Stdin = strings.NewReader(self.CmdString)
	} else {
		cmd = exec.Command("sh", "-c", self.CmdString)
	}

	// create the command, set the options
	if self.WorkingDirectory != "" {
		cmd.Dir = self.WorkingDirectory
	}
	cmd.Env = self.Environment
	if cmd.Env == nil {
		cmd.Env = os.Environ()
	}
	cmd.Stdout = self.Stdout
	cmd.Stderr = self.Stderr

	// cache the command running
	self.Cmd = cmd

	// start the command
	return cmd.Start()
}
开发者ID:himanshugpt,项目名称:evergreen,代码行数:26,代码来源:local_command.go

示例6: setupCommMapping

func setupCommMapping(cmd *exec.Cmd, comm *Mapping, rOut, wIn *os.File) {
	syscall.SetHandleInformation(syscall.Handle(comm.mapping), syscall.HANDLE_FLAG_INHERIT, 1)
	syscall.SetHandleInformation(syscall.Handle(rOut.Fd()), syscall.HANDLE_FLAG_INHERIT, 1)
	syscall.SetHandleInformation(syscall.Handle(wIn.Fd()), syscall.HANDLE_FLAG_INHERIT, 1)
	cmd.Env = append(cmd.Env, fmt.Sprintf("GO_FUZZ_COMM_FD=%v", comm.mapping))
	cmd.Env = append(cmd.Env, fmt.Sprintf("GO_FUZZ_IN_FD=%v", rOut.Fd()))
	cmd.Env = append(cmd.Env, fmt.Sprintf("GO_FUZZ_OUT_FD=%v", wIn.Fd()))
}
开发者ID:sjn1978,项目名称:go-fuzz,代码行数:8,代码来源:sys_windows.go

示例7: withEnv

func (runner *runner) withEnv(cmd *exec.Cmd) *exec.Cmd {
	if len(cmd.Env) == 0 {
		cmd.Env = append(os.Environ(), runner.env.Array()...)
	} else {
		cmd.Env = append(cmd.Env, runner.env.Array()...)
	}

	return cmd
}
开发者ID:nagyistoce,项目名称:garden-linux,代码行数:9,代码来源:runner.go

示例8: SetCmdEnv

func SetCmdEnv(cmd *exec.Cmd, key string, value string) error {
	if len(cmd.Env) == 0 {
		cmd.Env = os.Environ()
	}
	env, err := NewEnvFromArray(cmd.Env)
	if err != nil {
		return err
	}
	env.Values[key] = value
	cmd.Env = env.ToArray()
	return nil
}
开发者ID:iizotop,项目名称:kmg,代码行数:12,代码来源:SetCmdEnv.go

示例9: setGopath

func setGopath(cmd *exec.Cmd, gopath string) {
	cmd.Env = os.Environ()
	sawGopath := false
	for i := range cmd.Env {
		keyVal := strings.SplitN(cmd.Env[i], "=", 2)
		if keyVal[0] == "GOPATH" {
			cmd.Env[i] = "GOPATH=" + gopath + string(filepath.ListSeparator) + keyVal[1]
		}
	}
	if !sawGopath {
		cmd.Env = append(cmd.Env, "GOPATH="+gopath)
	}
}
开发者ID:philipmulcahy,项目名称:godebug,代码行数:13,代码来源:cmd.go

示例10: TestDoAll_cached_sample

func TestDoAll_cached_sample(t *testing.T) {
	cleanup("go-cache")

	var gitCmd *exec.Cmd
	var srcCmd *exec.Cmd
	gitCmd = exec.Command("git", "checkout", "071610bf3a597bc41aae05e27c5407444b7ea0d1")
	gitCmd.Dir = filepath.Join(testdataPath, "go-cached")
	if o, err := gitCmd.CombinedOutput(); err != nil {
		t.Fatal(string(o), err)
	}
	srcCmd = exec.Command("src", "do-all")
	srcCmd.Dir = filepath.Join(testdataPath, "go-cached")
	srcCmd.Env = append([]string{"SRCLIBPATH=" + srclibPath}, os.Environ()...)
	if o, err := srcCmd.CombinedOutput(); err != nil {
		t.Fatal(string(o), err)
	}
	gitCmd = exec.Command("git", "checkout", "34dd0f240fe12cdd8c9c6e24620cc0013518a55e")
	gitCmd.Dir = filepath.Join(testdataPath, "go-cached")
	if o, err := gitCmd.CombinedOutput(); err != nil {
		t.Fatal(string(o), err)
	}
	srcCmd = exec.Command("src", "do-all")
	srcCmd.Dir = filepath.Join(testdataPath, "go-cached")
	srcCmd.Env = append([]string{"SRCLIBPATH=" + srclibPath}, os.Environ()...)
	if o, err := srcCmd.CombinedOutput(); err != nil {
		t.Fatal(string(o), err)
	}
	firstOne, err := ioutil.ReadFile(filepath.Join(testdataPath, "go-cached", buildstore.BuildDataDirName, "071610bf3a597bc41aae05e27c5407444b7ea0d1", "one", "sample.graph.json"))
	if err != nil {
		t.Fatal(err)
	}
	secondOne, err := ioutil.ReadFile(filepath.Join(testdataPath, "go-cached", buildstore.BuildDataDirName, "34dd0f240fe12cdd8c9c6e24620cc0013518a55e", "one", "sample.graph.json"))
	if err != nil {
		t.Fatal(err)
	}
	if string(firstOne) != string(secondOne) {
		t.Error("Source unit \"one\" should have been cached: string(firstOne) != string(secondOne)")
	}
	firstTwo, err := ioutil.ReadFile(filepath.Join(testdataPath, "go-cached", buildstore.BuildDataDirName, "071610bf3a597bc41aae05e27c5407444b7ea0d1", "two", "sample.graph.json"))
	if err != nil {
		t.Fatal(err)
	}
	secondTwo, err := ioutil.ReadFile(filepath.Join(testdataPath, "go-cached", buildstore.BuildDataDirName, "34dd0f240fe12cdd8c9c6e24620cc0013518a55e", "two", "sample.graph.json"))
	if err != nil {
		t.Fatal(err)
	}
	if string(firstTwo) == string(secondTwo) {
		t.Error("Source unit \"two\" should not be cached: string(firstTwo) == string(secondTwo)")
	}
	cleanup("go-cache")
}
开发者ID:abec,项目名称:srclib,代码行数:51,代码来源:doall_cmd_test.go

示例11: runTestOnce

func runTestOnce(test test, mallocNumToFail int64) (passed bool, err error) {
	prog := path.Join(*buildDir, test[0])
	args := test[1:]
	var cmd *exec.Cmd
	if *useValgrind {
		cmd = valgrindOf(false, prog, args...)
	} else if *useCallgrind {
		cmd = callgrindOf(prog, args...)
	} else if *useGDB {
		cmd = gdbOf(prog, args...)
	} else {
		cmd = exec.Command(prog, args...)
	}
	var stdoutBuf bytes.Buffer
	var stderrBuf bytes.Buffer
	cmd.Stdout = &stdoutBuf
	cmd.Stderr = &stderrBuf
	if mallocNumToFail >= 0 {
		cmd.Env = os.Environ()
		cmd.Env = append(cmd.Env, "MALLOC_NUMBER_TO_FAIL="+strconv.FormatInt(mallocNumToFail, 10))
		if *mallocTestDebug {
			cmd.Env = append(cmd.Env, "MALLOC_ABORT_ON_FAIL=1")
		}
		cmd.Env = append(cmd.Env, "_MALLOC_CHECK=1")
	}

	if err := cmd.Start(); err != nil {
		return false, err
	}
	if err := cmd.Wait(); err != nil {
		if exitError, ok := err.(*exec.ExitError); ok {
			if exitError.Sys().(syscall.WaitStatus).ExitStatus() == 88 {
				return false, errMoreMallocs
			}
		}
		fmt.Print(string(stderrBuf.Bytes()))
		return false, err
	}
	fmt.Print(string(stderrBuf.Bytes()))

	// Account for Windows line-endings.
	stdout := bytes.Replace(stdoutBuf.Bytes(), []byte("\r\n"), []byte("\n"), -1)

	if bytes.HasSuffix(stdout, []byte("PASS\n")) &&
		(len(stdout) == 5 || stdout[len(stdout)-6] == '\n') {
		return true, nil
	}
	return false, nil
}
开发者ID:endlessm,项目名称:chromium-browser,代码行数:49,代码来源:all_tests.go

示例12: setCmdEnv

func setCmdEnv(cmd *exec.Cmd, username string) {
	userWorkspace := conf.GetUserWorkspace(username)

	cmd.Env = append(cmd.Env,
		"GOPATH="+userWorkspace,
		"GOOS="+runtime.GOOS,
		"GOARCH="+runtime.GOARCH,
		"GOROOT="+runtime.GOROOT(),
		"PATH="+os.Getenv("PATH"))

	if util.OS.IsWindows() {
		// FIXME: for some weird issues on Windows, such as: The requested service provider could not be loaded or initialized.
		cmd.Env = append(cmd.Env, os.Environ()...)
	}
}
开发者ID:EricRobert,项目名称:wide,代码行数:15,代码来源:outputs.go

示例13: Capture

// Capture runs an executable from a directory returns the output, exit code
// and error if appropriate. It sets the environment variables specified.
func Capture(wd string, env []string, args ...string) (string, int, error) {
	exitCode := -1
	//log.Printf("Capture(%s, %s, %s)", wd, env, args)
	var c *exec.Cmd
	switch len(args) {
	case 0:
		return "", -1, errors.New("no command specified")
	case 1:
		c = exec.Command(args[0])
	default:
		c = exec.Command(args[0], args[1:]...)
	}
	if wd == "" {
		return "", -1, errors.New("wd is required")
	}
	c.Dir = wd
	procEnv := map[string]string{}
	for _, item := range os.Environ() {
		items := strings.SplitN(item, "=", 2)
		procEnv[items[0]] = items[1]
	}
	procEnv["LANG"] = "en_US.UTF-8"
	procEnv["LANGUAGE"] = "en_US.UTF-8"
	for _, item := range env {
		items := strings.SplitN(item, "=", 2)
		if items[1] == "" {
			// Remove it instead.
			delete(procEnv, items[0])
		} else {
			procEnv[items[0]] = items[1]
		}
	}
	c.Env = make([]string, 0, len(procEnv))
	for k, v := range procEnv {
		c.Env = append(c.Env, k+"="+v)
	}
	out, err := c.CombinedOutput()
	if c.ProcessState != nil {
		if waitStatus, ok := c.ProcessState.Sys().(syscall.WaitStatus); ok {
			exitCode = waitStatus.ExitStatus()
			if exitCode != 0 {
				err = nil
			}
		}
	}
	// TODO(maruel): Handle code page on Windows.
	return string(out), exitCode, err
}
开发者ID:nodirt,项目名称:pre-commit-go,代码行数:50,代码来源:utils.go

示例14: setupCommand

func setupCommand(cmd *exec.Cmd, taskp TaskDef, outdir string, replacements map[string]string) (stdin, stdout string, err error) {
	if taskp.Vwd != nil {
		for k, v := range taskp.Vwd {
			v = substitute(v, replacements)
			err = checkOutputFilename(outdir, k)
			if err != nil {
				return "", "", err
			}
			os.Symlink(v, outdir+"/"+k)
		}
	}

	if taskp.Stdin != "" {
		// Set up stdin redirection
		stdin = substitute(taskp.Stdin, replacements)
		cmd.Stdin, err = os.Open(stdin)
		if err != nil {
			return "", "", err
		}
	}

	if taskp.Stdout != "" {
		err = checkOutputFilename(outdir, taskp.Stdout)
		if err != nil {
			return "", "", err
		}
		// Set up stdout redirection
		stdout = outdir + "/" + taskp.Stdout
		cmd.Stdout, err = os.Create(stdout)
		if err != nil {
			return "", "", err
		}
	} else {
		cmd.Stdout = os.Stdout
	}

	cmd.Stderr = os.Stderr

	if taskp.Env != nil {
		// Set up subprocess environment
		cmd.Env = os.Environ()
		for k, v := range taskp.Env {
			v = substitute(v, replacements)
			cmd.Env = append(cmd.Env, k+"="+v)
		}
	}
	return stdin, stdout, nil
}
开发者ID:pombredanne,项目名称:arvados,代码行数:48,代码来源:crunchrunner.go

示例15: pluginInfo

func pluginInfo(name string) (ver, short, long string) {
	if os.Getenv("HKPLUGINMODE") == "info" {
		return "", "plugin exec loop", "plugin exec loop"
	}
	short = "no description"
	long = name + ": unknown description"
	var cmd exec.Cmd
	cmd.Args = []string{name}
	cmd.Path = lookupPlugin(name)
	cmd.Env = append([]string{"HKPLUGINMODE=info"}, os.Environ()...)
	buf, err := cmd.Output()
	if err != nil {
		return
	}
	info := string(buf)
	if !strings.HasPrefix(info, name+" ") {
		return
	}
	info = info[len(name)+1:]
	i := strings.Index(info, ": ")
	if i < 0 {
		return
	}
	ver, info = info[:i], info[i+2:]
	i = strings.Index(info, "\n\n")
	if i < 0 || 50 < i || strings.Contains(info[:i], "\n") {
		return
	}
	short, long = info[:i], info[i+2:]
	return ver, strings.TrimSpace(short), strings.TrimSpace(long)
}
开发者ID:shaunduncan,项目名称:hk,代码行数:31,代码来源:plugin.go


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