本文整理汇总了Golang中os/exec.Cmd.Start方法的典型用法代码示例。如果您正苦于以下问题:Golang Cmd.Start方法的具体用法?Golang Cmd.Start怎么用?Golang Cmd.Start使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os/exec.Cmd
的用法示例。
在下文中一共展示了Cmd.Start方法的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
}
示例2: source
func source(dir, from, to string) <-chan string {
var cmd *exec.Cmd
if to == "" {
cmd = exec.Command("git", "-C", dir, "log", `--pretty=format:hash: %H%n-----%nauthor: %an <%ae>%n-----%nrawSubject: %s%n-----%nrawBody: %b%n-----%nEND-COMMIT%n`, from)
} else {
cmd = exec.Command("git", "-C", dir, "log", `--pretty=format:hash: %H%n-----%nauthor: %an <%ae>%n-----%nrawSubject: %s%n-----%nrawBody: %b%n-----%nEND-COMMIT%n`, to+".."+from)
}
outputChannel := make(chan string)
output, err := cmd.StdoutPipe()
if err != nil {
panic(err)
}
err = cmd.Start()
if err != nil {
log.Fatal(err)
}
go func() {
scanner := bufio.NewScanner(output)
for scanner.Scan() {
outputChannel <- scanner.Text()
}
defer output.Close()
close(outputChannel)
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
}()
return outputChannel
}
示例3: execCommand
func execCommand(cmd *exec.Cmd) error {
cmdReader, err := cmd.StdoutPipe()
if err != nil {
fmt.Fprintln(os.Stderr, "Error creating StdoutPipe for Cmd", err)
return err
}
scanner := bufio.NewScanner(cmdReader)
go func() {
for scanner.Scan() {
fmt.Printf("docker build out | %s\n", scanner.Text())
}
}()
var stderr bytes.Buffer
cmd.Stdout = os.Stdout
cmd.Stderr = &stderr
err = cmd.Start()
if err != nil {
fmt.Printf("docker build out | %s\n", stderr.String())
return err
}
err = cmd.Wait()
if err != nil {
fmt.Printf("docker build out | %s\n", stderr.String())
return err
}
return err
}
示例4: send
// send produces a binary diff stream and passes it to cont
func send(repo, commit string, cont func(io.Reader) error) error {
parent := GetMeta(path.Join(repo, commit), "parent")
var cmd *exec.Cmd
if parent == "" {
cmd = exec.Command("btrfs", "send", FilePath(path.Join(repo, commit)))
} else {
cmd = exec.Command("btrfs", "send", "-p", FilePath(path.Join(repo, parent)), FilePath(path.Join(repo, commit)))
}
stdin, stdout := io.Pipe()
stderr := bytes.NewBuffer(nil)
cmd.Stdout = stdout
if err := cmd.Start(); err != nil {
return err
}
errC := make(chan error, 1)
go func() {
errC <- cont(stdin)
}()
waitErr := cmd.Wait()
closeErr := stdout.Close()
if waitErr != nil {
return fmt.Errorf("%s %s", waitErr.Error(), stderr.String())
}
if closeErr != nil {
return closeErr
}
return <-errC
}
示例5: reloadHAproxy
func (this *Start) reloadHAproxy() (err error) {
var cmd *exec.Cmd = nil
waitStartCh := make(chan struct{})
if this.starting {
log.Info("haproxy starting")
cmd = exec.Command(this.command, "-f", configFile) // TODO use absolute path
this.starting = false
go func() {
<-waitStartCh
log.Info("haproxy started")
if err := cmd.Wait(); err != nil {
log.Error("haproxy: %v", err)
}
}()
} else {
shellScript := fmt.Sprintf("%s -f %s/%s -sf `cat %s/%s`",
this.command, this.root, configFile, this.root, haproxyPidFile)
log.Info("haproxy reloading: %s", shellScript)
cmd = exec.Command("/bin/sh", "-c", shellScript)
go func() {
<-waitStartCh
log.Info("haproxy reloaded")
if err := cmd.Wait(); err != nil {
log.Error("haproxy: %v", err)
}
}()
}
if err = cmd.Start(); err == nil {
waitStartCh <- struct{}{}
}
return err
}
示例6: RunCommandWithStdoutStderr
// RunCommandWithStdoutStderr execs a command and returns its output.
func RunCommandWithStdoutStderr(cmd *exec.Cmd) (bytes.Buffer, bytes.Buffer, error) {
var stdout, stderr bytes.Buffer
stderrPipe, err := cmd.StderrPipe()
stdoutPipe, err := cmd.StdoutPipe()
cmd.Env = os.Environ()
if err != nil {
fmt.Println("error at io pipes")
}
err = cmd.Start()
if err != nil {
fmt.Println("error at command start")
}
go func() {
io.Copy(&stdout, stdoutPipe)
fmt.Println(stdout.String())
}()
go func() {
io.Copy(&stderr, stderrPipe)
fmt.Println(stderr.String())
}()
time.Sleep(2000 * time.Millisecond)
err = cmd.Wait()
if err != nil {
fmt.Println("error at command wait")
}
return stdout, stderr, err
}
示例7: runTest
func runTest(test test) (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 {
cmd = exec.Command(prog, args...)
}
var stdoutBuf bytes.Buffer
cmd.Stdout = &stdoutBuf
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
return false, err
}
if err := cmd.Wait(); err != nil {
return false, err
}
// 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
}
示例8: 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
}
示例9: timedCommand
// timedCommand executes the given command, terminating it forcefully
// if it is still running after the given timeout elapses.
func (e *executor) timedCommand(timeout time.Duration, opts opts, command *exec.Cmd) error {
// Make the process of this command a new process group leader
// to facilitate clean up of processes that time out.
command.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
// Kill this process group explicitly when receiving SIGTERM
// or SIGINT signals.
sigchan := make(chan os.Signal, 1)
signal.Notify(sigchan, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGINT)
go func() {
<-sigchan
e.terminateProcessGroup(opts, command)
}()
if err := command.Start(); err != nil {
e.printf(e.verboseStdout(opts), "FAILED: %v", err)
return err
}
done := make(chan error, 1)
go func() {
done <- command.Wait()
}()
select {
case <-time.After(timeout):
// The command has timed out.
e.terminateProcessGroup(opts, command)
// Allow goroutine to exit.
<-done
e.printf(e.verboseStdout(opts), "TIMED OUT")
return commandTimedOutErr
case err := <-done:
e.printf(e.verboseStdout(opts), okOrFailed(err))
return err
}
}
示例10: start
func start(c *exec.Cmd) (pty *os.File, err error) {
pty, tty, err := open()
if err != nil {
return nil, err
}
defer tty.Close()
err = setEcho(pty, false)
if err != nil {
return nil, err
}
err = setEcho(tty, false)
if err != nil {
return nil, err
}
c.Stdout = tty
c.Stdin = tty
c.Stderr = tty
if c.SysProcAttr == nil {
c.SysProcAttr = &syscall.SysProcAttr{}
}
c.SysProcAttr.Setctty = true
c.SysProcAttr.Setsid = true
err = c.Start()
if err != nil {
pty.Close()
return nil, err
}
return pty, err
}
示例11: CmdStream
func CmdStream(cmd *exec.Cmd) (io.Reader, error) {
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return nil, err
}
pipeR, pipeW := io.Pipe()
go func() {
_, err := io.Copy(pipeW, stdout)
if err != nil {
pipeW.CloseWithError(err)
}
errText, e := ioutil.ReadAll(stderr)
if e != nil {
errText = []byte("(...couldn't fetch stderr: " + e.Error() + ")")
}
if err := cmd.Wait(); err != nil {
// FIXME: can this block if stderr outputs more than the size of StderrPipe()'s buffer?
pipeW.CloseWithError(errors.New(err.Error() + ": " + string(errText)))
} else {
pipeW.Close()
}
}()
if err := cmd.Start(); err != nil {
return nil, err
}
return pipeR, nil
}
示例12: cmdTimeout
// cmdTimeout runs the command c and returns a timeout if it doesn't complete
// after time t. If a timeout occurs, cmdTimeout will kill the process. Blocks
// until the process terminates.
func cmdTimeout(c *exec.Cmd, t time.Duration) error {
log.Debug("cmdTimeout: %v", c)
start := time.Now()
if err := c.Start(); err != nil {
return fmt.Errorf("cmd start: %v", err)
}
done := make(chan error)
go func() {
done <- c.Wait()
close(done)
}()
select {
case <-time.After(t):
log.Debug("killing cmd %v", c)
err := c.Process.Kill()
// Receive from done so that we don't leave the goroutine hanging
err2 := <-done
// Kill error takes precedence as they should be unexpected
if err != nil {
return err
}
return err2
case err := <-done:
log.Debug("cmd %v completed in %v", c, time.Now().Sub(start))
return err
}
}
示例13: Run
func (cmd *execCmd) Run(fs *flag.FlagSet) {
cmd.InitClient(false)
cmd.exitStatus = 0
cmd.ValidateFlags()
args := fs.Args()
if len(args) < 1 {
fmt.Println("no command to exec")
os.Exit(1)
return
}
var c *exec.Cmd
if len(args) > 2 {
c = exec.Command(args[0], args[1:]...)
} else {
c = exec.Command(args[0])
}
attachCmd(c)
err := c.Start()
if err != nil {
panic(err)
}
cmd.RegisterWithExitHook(map[string]string(*cmd.services), false)
exitCh := exitStatusCh(c)
cmd.exitStatus = int(<-exitCh)
close(cmd.exitSignalCh)
time.Sleep(time.Second)
}
示例14: main
func main() {
defer func() {
if r := recover(); r != nil {
var err string
switch r.(type) {
case string:
err = r.(string)
break
case error:
err = r.(error).Error()
default:
err = fmt.Sprintf("%v", err)
}
url := fmt.Sprintf("http://stackoverflow.com/search?q=[go]%%20%s", url.QueryEscape(err))
var cmd *exec.Cmd
switch runtime.GOOS {
case "windows":
cmd = exec.Command("cmd", "/c", "start", url)
break
case "darwin":
cmd = exec.Command("open", url)
break
default:
cmd = exec.Command("xdg-open", url)
break
}
cmd.Start()
}
}()
// naughty code here
}
示例15: Publish
// Publish prints the result of a check to stdout.
func (p *ExecPublisher) Publish(result *CheckResult) error {
var cmd *exec.Cmd
if len(p.cmd) > 1 {
cmd = exec.Command(p.cmd[0], p.cmd[1:]...)
} else {
cmd = exec.Command(p.cmd[0])
}
var b bytes.Buffer
cmd.Stdout = &b
cmd.Stderr = &b
stdin, err := cmd.StdinPipe()
if err != nil {
return err
}
if err = cmd.Start(); err != nil {
p.log.Error("Exec failed", "error", err)
return err
}
if err = p.stdinTemplate.Execute(stdin, result); err != nil {
p.log.Error("Failed to write template data to stdin", "error", err)
return err
}
stdin.Close()
if err = cmd.Wait(); err != nil {
p.log.Error("Exec failed", "error", err, "output", b.String())
return err
}
return nil
}