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


Golang exec.Cmd类代码示例

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


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

示例1: ExecBin

func (w *Worker) ExecBin(binPath string, args []string, maxRunTime int64) (string, error) {
	var cmd *exec.Cmd
	var stdout bytes.Buffer
	var stderr bytes.Buffer
	var err error

	if len(args) == 0 {
		cmd = exec.Command(binPath)
	} else {
		cmd = exec.Command(binPath, args...)
	}

	cmd.Stdout = &stdout
	cmd.Stderr = &stderr
	cmd.Start() // attention!

	err, _ = w.CmdRunWithTimeout(cmd,
		time.Duration(maxRunTime)*time.Second,
	)
	if err != nil {
		return "", err
	}
	if len(stderr.String()) != 0 {
		errMsg := strings.TrimRight(stderr.String(), "\n")
		return "", errors.NewError(errMsg)
	}

	return strings.TrimRight(stdout.String(), "\n"), nil
}
开发者ID:jameswei,项目名称:kingtask,代码行数:29,代码来源:worker.go

示例2: init

func init() {
	registerCommand(&cmd.Command{
		Name:      "doc",
		UsageLine: `doc <pkg> <sym>[.<method>]`,
		Short:     "show documentation for a package or symbol",
		Long: `
Doc shows documentation for a package or symbol.

See 'go help doc'.
`,
		Run: func(ctx *gb.Context, args []string) error {
			env := cmd.MergeEnv(os.Environ(), map[string]string{
				"GOPATH": fmt.Sprintf("%s:%s", ctx.Projectdir(), filepath.Join(ctx.Projectdir(), "vendor")),
			})
			if len(args) == 0 {
				args = append(args, ".")
			}
			args = append([]string{filepath.Join(ctx.Context.GOROOT, "bin", "godoc")}, args...)

			cmd := exec.Cmd{
				Path: args[0],
				Args: args,
				Env:  env,

				Stdin:  os.Stdin,
				Stdout: os.Stdout,
				Stderr: os.Stderr,
			}
			return cmd.Run()
		},
		ParseArgs: func(_ *gb.Context, _ string, args []string) []string { return args },
	})
}
开发者ID:kalafut,项目名称:gb,代码行数:33,代码来源:doc.go

示例3: TestStatStdin

func TestStatStdin(t *testing.T) {
	switch runtime.GOOS {
	case "android", "plan9":
		t.Skipf("%s doesn't have /bin/sh", runtime.GOOS)
	}

	testenv.MustHaveExec(t)

	if Getenv("GO_WANT_HELPER_PROCESS") == "1" {
		st, err := Stdin.Stat()
		if err != nil {
			t.Fatalf("Stat failed: %v", err)
		}
		fmt.Println(st.Mode() & ModeNamedPipe)
		Exit(0)
	}

	var cmd *osexec.Cmd
	if runtime.GOOS == "windows" {
		cmd = osexec.Command("cmd", "/c", "echo output | "+Args[0]+" -test.run=TestStatStdin")
	} else {
		cmd = osexec.Command("/bin/sh", "-c", "echo output | "+Args[0]+" -test.run=TestStatStdin")
	}
	cmd.Env = append(Environ(), "GO_WANT_HELPER_PROCESS=1")

	output, err := cmd.CombinedOutput()
	if err != nil {
		t.Fatalf("Failed to spawn child process: %v %q", err, string(output))
	}

	// result will be like "prw-rw-rw"
	if len(output) < 1 || output[0] != 'p' {
		t.Fatalf("Child process reports stdin is not pipe '%v'", string(output))
	}
}
开发者ID:duhaibo0404,项目名称:go-1,代码行数:35,代码来源:os_test.go

示例4: Reload

// Configuration reload
func Reload(binary, config, pidfile string) error {

	pid, err := ioutil.ReadFile(pidfile)
	if err != nil {
		return err
	}

	/* 	Setup all the command line parameters so we get an executable similar to
	/usr/local/bin/haproxy -f resources/haproxy_new.cfg -p resources/haproxy-private.pid -st 1234

	*/
	arg0 := "-f"
	arg1 := config
	arg2 := "-p"
	arg3 := pidfile
	arg4 := "-st"
	arg5 := strings.Trim(string(pid), "\n")
	var cmd *exec.Cmd

	// If this is the first run, the PID value will be empty, otherwise it will be > 0
	if len(arg5) > 0 {
		cmd = exec.Command(binary, arg0, arg1, arg2, arg3, arg4, arg5)
	} else {
		cmd = exec.Command(binary, arg0, arg1, arg2, arg3)
	}
	var out bytes.Buffer
	cmd.Stdout = &out
	cmdErr := cmd.Run()
	if cmdErr != nil {
		fmt.Println(cmdErr.Error())
		return cmdErr
	}
	log.Info("HaproxyReload: " + out.String() + string(pid))
	return nil
}
开发者ID:Oakleon,项目名称:haproxy-rest,代码行数:36,代码来源:haproxy.go

示例5: checkVersionPackageExact

func (spec SpecPackage) checkVersionPackageExact(defaults PlatformDefaults) (err error) {
	var cmd *exec.Cmd
	var verRex string

	switch spec.Type {
	case "homebrew":
		// sbt 0.12.3 0.12.4 0.13.0
		cmd = exec.Command("/usr/local/bin/brew", "ls", "--versions", spec.Name)
		verRex = " " + spec.Version + "( |$)"
	default:
		return errors.New("Unknown package manager type " + spec.Type)
	}

	out, err := cmd.Output()
	if err != nil {
		return err
	}

	re, err := regexp.Compile(verRex)
	if err != nil {
		return fmt.Errorf("Bad verRex %s for package manager type %s", verRex, spec.Type)
	}

	if re.FindIndex(out) == nil && !spec.Absent {
		return errors.New("No such version installed")
	}

	return nil
}
开发者ID:vivus-ignis,项目名称:libnodespec,代码行数:29,代码来源:spec_package.go

示例6: startContainer

// startContainer starts the container. Returns the exit status or -1 and an
// error.
//
// Signals sent to the current process will be forwarded to container.
func startContainer(container *libcontainer.Config, term namespaces.Terminal, dataPath string, args []string) (int, error) {
	var (
		cmd  *exec.Cmd
		sigc = make(chan os.Signal, 10)
	)

	signal.Notify(sigc)

	createCommand := func(container *libcontainer.Config, console, rootfs, dataPath, init string, pipe *os.File, args []string) *exec.Cmd {
		cmd = namespaces.DefaultCreateCommand(container, console, rootfs, dataPath, init, pipe, args)
		if logPath != "" {
			cmd.Env = append(cmd.Env, fmt.Sprintf("log=%s", logPath))
		}
		return cmd
	}

	startCallback := func() {
		go func() {
			for sig := range sigc {
				cmd.Process.Signal(sig)
			}
		}()
	}

	return namespaces.Exec(container, term, "", dataPath, args, createCommand, startCallback)
}
开发者ID:kieslee,项目名称:docker,代码行数:30,代码来源:exec.go

示例7: runCommandWithOutput

func runCommandWithOutput(cmd *exec.Cmd) (output string, exitCode int, err error) {
	exitCode = 0
	out, err := cmd.CombinedOutput()
	exitCode = processExitCode(err)
	output = string(out)
	return
}
开发者ID:baoruxing,项目名称:docker,代码行数:7,代码来源:utils.go

示例8: RedirectIOTo

func RedirectIOTo(cmd *exec.Cmd, myin io.Reader, myout, myerr io.Writer) {
	// redirect IO
	cmd.Stdout = myout
	cmd.Stderr = myerr
	cmd.Stdin = myin
	//return nil, err
}
开发者ID:yl10,项目名称:goxc,代码行数:7,代码来源:exec.go

示例9: babysitRootProcess

func (s *SlaveNode) babysitRootProcess(cmd *exec.Cmd) {
	// We want to let this process run "forever", but it will eventually
	// die... either on program termination or when its dependencies change
	// and we kill it. when it's requested to restart, err is "signal 9",
	// and we do nothing.
	s.trace("running the root command now")
	output, err := cmd.CombinedOutput()
	if err == nil {
		// TODO
		s.trace("root process exited; output was: %s", output)
		println(string(output))
		/* ErrorConfigCommandCrashed(string(output)) */
	}
	msg := err.Error()
	if s.hasSuccessfullyBooted == false {
		// TODO
		s.trace("root process exited with an error before it could boot: %s; output was: %s", msg, output)
		println(msg)
		/* ErrorConfigCommandCouldntStart(msg, string(output)) */
	} else if msg == "signal 9" {
		s.trace("root process exited because we killed it & it will be restarted: %s; output was: %s", msg, output)
	} else {
		s.L.Lock()
		defer s.L.Unlock()
		if s.State == SUnbooted {
			s.trace("root process exited with error. Sending it to crashed state. Message was: %s; output: %s", msg, output)
			s.Error = fmt.Sprintf("Zeus root process (%s) died with message %s:\n%s", s.Name, msg, output)
			s.event <- true
		} else {
			s.trace("Unexpected state for root process to be in at this time: %s", s.State)
		}
	}
}
开发者ID:grosser,项目名称:zeus,代码行数:33,代码来源:slavenode.go

示例10: mountDataset

func (b *Provider) mountDataset(vol *zfsVolume) error {
	// mount the dataset, snapshots will be readonly
	// 'zfs mount' currently can't perform on snapshots; seealso https://github.com/zfsonlinux/zfs/issues/173
	alreadyMounted, err := isMount(vol.basemount)
	if err != nil {
		return fmt.Errorf("could not mount: %s", err)
	}
	if alreadyMounted {
		return nil
	}
	if err = os.MkdirAll(vol.basemount, 0644); err != nil {
		return fmt.Errorf("could not mount: %s", err)
	}
	var buf bytes.Buffer
	var cmd *exec.Cmd
	if vol.IsSnapshot() {
		cmd = exec.Command("mount", "-tzfs", vol.dataset.Name, vol.basemount)
	} else {
		cmd = exec.Command("zfs", "mount", vol.dataset.Name)
	}
	cmd.Stderr = &buf
	if err := cmd.Run(); err != nil {
		return fmt.Errorf("could not mount: %s (%s)", err, strings.TrimSpace(buf.String()))
	}
	return nil
}
开发者ID:eldarion-gondor,项目名称:cli,代码行数:26,代码来源:zfs.go

示例11: waitSimple

func waitSimple(command *Command, cmd *osexec.Cmd) error {
	err := cmd.Wait()
	if err != nil {
		glog.Errorf("Command exited with %s: %s", err, DebugString(command))
	}
	return err
}
开发者ID:1394,项目名称:skia-buildbot,代码行数:7,代码来源:exec.go

示例12: runInContext

// runInContext runs a command in the context of a Vagrantfile (from the same dir)
func runInContext(cmd *exec.Cmd) error {

	// run the command from ~/.nanobox/apps/<config.App>. Running the command from
	// the directory that contains the Vagratfile ensure that the command can
	// atleast run (especially in cases like 'create' where a VM hadn't been created
	// yet, and a UUID isn't available)
	setContext(config.AppDir)

	//
	handleCMDout(cmd)

	// start the command; we need this to 'fire and forget' so that we can manually
	// capture and modify the commands output above
	if err := cmd.Start(); err != nil {
		return err
	}

	// wait for the command to complete/fail and exit, giving us a chance to scan
	// the output
	if err := cmd.Wait(); err != nil {
		return err
	}

	// switch back to project dir
	setContext(config.CWDir)

	return nil
}
开发者ID:johan48191,项目名称:nanobox,代码行数:29,代码来源:vagrant.go

示例13: Start

/*
Start starts the passed-in *exec.Cmd command.  It wraps the command in a *gexec.Session.

The session pipes the command's stdout and stderr to two *gbytes.Buffers available as properties on the session: session.Out and session.Err.
These buffers can be used with the gbytes.Say matcher to match against unread output:

	Ω(session.Out).Should(gbytes.Say("foo-out"))
	Ω(session.Err).Should(gbytes.Say("foo-err"))

In addition, Session satisfies the gbytes.BufferProvider interface and provides the stdout *gbytes.Buffer.  This allows you to replace the first line, above, with:

	Ω(session).Should(gbytes.Say("foo-out"))

When outWriter and/or errWriter are non-nil, the session will pipe stdout and/or stderr output both into the session *gybtes.Buffers and to the passed-in outWriter/errWriter.
This is useful for capturing the process's output or logging it to screen.  In particular, when using Ginkgo it can be convenient to direct output to the GinkgoWriter:

	session, err := Start(command, GinkgoWriter, GinkgoWriter)

This will log output when running tests in verbose mode, but - otherwise - will only log output when a test fails.

The session wrapper is responsible for waiting on the *exec.Cmd command.  You *should not* call command.Wait() yourself.
Instead, to assert that the command has exited you can use the gexec.Exit matcher:

	Ω(session).Should(gexec.Exit())

When the session exits it closes the stdout and stderr gbytes buffers.  This will short circuit any
Eventuallys waiting fo the buffers to Say something.
*/
func Start(command *exec.Cmd, outWriter io.Writer, errWriter io.Writer) (*Session, error) {
	exited := make(chan struct{})

	session := &Session{
		Command:  command,
		Out:      gbytes.NewBuffer(),
		Err:      gbytes.NewBuffer(),
		Exited:   exited,
		lock:     &sync.Mutex{},
		exitCode: -1,
	}

	var commandOut, commandErr io.Writer

	commandOut, commandErr = session.Out, session.Err

	if outWriter != nil && !reflect.ValueOf(outWriter).IsNil() {
		commandOut = io.MultiWriter(commandOut, outWriter)
	}

	if errWriter != nil && !reflect.ValueOf(errWriter).IsNil() {
		commandErr = io.MultiWriter(commandErr, errWriter)
	}

	command.Stdout = commandOut
	command.Stderr = commandErr

	err := command.Start()
	if err == nil {
		go session.monitorForExit(exited)
	}

	return session, err
}
开发者ID:viovanov,项目名称:bosh-agent,代码行数:62,代码来源:session.go

示例14: CmdRunWithTimeout

func (w *Worker) CmdRunWithTimeout(cmd *exec.Cmd, timeout time.Duration) (error, bool) {
	done := make(chan error)
	go func() {
		done <- cmd.Wait()
	}()

	var err error
	select {
	case <-time.After(timeout):
		// timeout
		if err = cmd.Process.Kill(); err != nil {
			golog.Error("worker", "CmdRunTimeout", "kill error", 0,
				"path", cmd.Path,
				"error", err.Error(),
			)
		}
		golog.Info("worker", "CmdRunWithTimeout", "kill process", 0,
			"path", cmd.Path,
			"error", errors.ErrExecTimeout.Error(),
		)
		go func() {
			<-done // allow goroutine to exit
		}()
		return errors.ErrExecTimeout, true
	case err = <-done:
		return err, false
	}
}
开发者ID:jameswei,项目名称:kingtask,代码行数:28,代码来源:worker.go

示例15: runFn

// "run" let's the user execute arbitrary commands
func runFn(args []interface{}) (interface{}, error) {
	if len(args) < 1 {
		return nil, errors.New("run takes at least one argument")
	}

	commands := []string{}
	for _, arg := range args {
		if s, ok := arg.(string); ok {
			commands = append(commands, s)
		} else {
			return nil, errors.New("run only takes string arguments")
		}
	}

	var cmd *exec.Cmd
	if len(commands) == 1 {
		cmd = exec.Command(commands[0])
	} else {
		cmd = exec.Command(commands[0], commands[1:]...)
	}
	log.Printf("executing command '%s' with arguments: %s\n", commands[0], strings.Join(commands[1:], ","))

	if err := cmd.Run(); err == nil {
		cmd.Wait()
	}

	return nil, nil
}
开发者ID:drtoful,项目名称:gifttt,代码行数:29,代码来源:rule.go


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