本文整理汇总了Golang中os/exec.Cmd.Run方法的典型用法代码示例。如果您正苦于以下问题:Golang Cmd.Run方法的具体用法?Golang Cmd.Run怎么用?Golang Cmd.Run使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os/exec.Cmd
的用法示例。
在下文中一共展示了Cmd.Run方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: run
func run(c *exec.Cmd) error {
r := c.Run()
if r != nil {
return fmt.Errorf("%s %s: %s", c.Path, c.Args[0], r)
}
return nil
}
示例2: run
func run(src string) error {
// Create a temp folder.
tempDir, err := ioutil.TempDir("", "goexec_")
if err != nil {
return err
}
defer func() {
err := os.RemoveAll(tempDir)
if err != nil {
fmt.Fprintln(os.Stderr, "warning: error removing temp dir:", err)
}
}()
// Write the source code file.
tempFile := filepath.Join(tempDir, "gen.go")
err = ioutil.WriteFile(tempFile, []byte(src), 0600)
if err != nil {
return err
}
// Compile and run the program.
var cmd *exec.Cmd
switch *compilerFlag {
case "gc":
cmd = exec.Command("go", "run", tempFile)
case "gopherjs":
cmd = exec.Command("gopherjs", "run", tempFile)
}
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
示例3: verifyCertWithSystem
func verifyCertWithSystem(block *pem.Block, add func(*Certificate)) {
data := pem.EncodeToMemory(block)
var cmd *exec.Cmd
if needsTmpFiles() {
f, err := ioutil.TempFile("", "cert")
if err != nil {
fmt.Fprintf(os.Stderr, "can't create temporary file for cert: %v", err)
return
}
defer os.Remove(f.Name())
if _, err := f.Write(data); err != nil {
fmt.Fprintf(os.Stderr, "can't write temporary file for cert: %v", err)
return
}
if err := f.Close(); err != nil {
fmt.Fprintf(os.Stderr, "can't write temporary file for cert: %v", err)
return
}
cmd = exec.Command("/usr/bin/security", "verify-cert", "-c", f.Name(), "-l")
} else {
cmd = exec.Command("/usr/bin/security", "verify-cert", "-c", "/dev/stdin", "-l")
cmd.Stdin = bytes.NewReader(data)
}
if cmd.Run() == nil {
// Non-zero exit means untrusted
cert, err := ParseCertificate(block.Bytes)
if err != nil {
return
}
add(cert)
}
}
示例4: ExecAdd
// ExecAdd executes IPAM plugin, assuming CNI_COMMAND == ADD.
// Parses and returns resulting IPConfig
func ExecAdd(plugin string, netconf []byte) (*Result, error) {
if os.Getenv("CNI_COMMAND") != "ADD" {
return nil, fmt.Errorf("CNI_COMMAND is not ADD")
}
pluginPath := Find(plugin)
if pluginPath == "" {
return nil, fmt.Errorf("could not find %q plugin", plugin)
}
stdout := &bytes.Buffer{}
c := exec.Cmd{
Path: pluginPath,
Args: []string{pluginPath},
Stdin: bytes.NewBuffer(netconf),
Stdout: stdout,
Stderr: os.Stderr,
}
if err := c.Run(); err != nil {
return nil, pluginErr(err, stdout.Bytes())
}
res := &Result{}
err := json.Unmarshal(stdout.Bytes(), res)
return res, err
}
示例5: Unmount
// Unmount attempts to unmount the provided FUSE mount point, forcibly
// if necessary.
func Unmount(point string) error {
fmt.Printf("Unmounting %s...\n", point)
var cmd *exec.Cmd
switch runtime.GOOS {
case "darwin":
cmd = exec.Command("diskutil", "umount", "force", point)
case "linux":
cmd = exec.Command("fusermount", "-u", point)
default:
return fmt.Errorf("unmount: unimplemented")
}
errc := make(chan error, 1)
go func() {
if err := exec.Command("umount", point).Run(); err == nil {
errc <- err
}
// retry to unmount with the fallback cmd
errc <- cmd.Run()
}()
select {
case <-time.After(1 * time.Second):
return fmt.Errorf("umount timeout")
case err := <-errc:
return err
}
}
示例6: Open
func (gb GenericBrowser) Open(s string) error {
u, err := url.Parse(s)
if err != nil {
return err
}
// Enforce a scheme (windows requires scheme to be set to work properly).
if u.Scheme != "https" {
u.Scheme = "http"
}
s = u.String()
// Escape characters not allowed by cmd/bash
switch runtime.GOOS {
case "windows":
s = strings.Replace(s, "&", `^&`, -1)
}
var cmd *exec.Cmd
if gb.Args != nil {
cmd = exec.Command(gb.Cmd, append(gb.Args, s)...)
} else {
cmd = exec.Command(gb.Cmd, s)
}
return cmd.Run()
}
示例7: runCommandWithOutputForDuration
func runCommandWithOutputForDuration(cmd *exec.Cmd, duration time.Duration) (output string, exitCode int, timedOut bool, err error) {
var outputBuffer bytes.Buffer
if cmd.Stdout != nil {
err = errors.New("cmd.Stdout already set")
return
}
cmd.Stdout = &outputBuffer
if cmd.Stderr != nil {
err = errors.New("cmd.Stderr already set")
return
}
cmd.Stderr = &outputBuffer
done := make(chan error)
go func() {
exitErr := cmd.Run()
exitCode = processExitCode(exitErr)
done <- exitErr
}()
select {
case <-time.After(duration):
killErr := cmd.Process.Kill()
if killErr != nil {
fmt.Printf("failed to kill (pid=%d): %v\n", cmd.Process.Pid, killErr)
}
timedOut = true
break
case err = <-done:
break
}
output = outputBuffer.String()
return
}
示例8: Resize
func (i *Image) Resize(dst, format string, w, h, q int, optimize bool) error {
wh := fmt.Sprintf("%dx%d", w, h)
if w == 0 {
wh = fmt.Sprintf("x%d", h)
}
if h == 0 {
wh = fmt.Sprintf("%d", w)
}
if format == "" {
format = i.Type
}
dstImagick := format + ":" + dst
var cmd *exec.Cmd
if q > 0 {
cmd = exec.Command("convert", i.Filename, "-strip", "-resize", wh, "-quality", fmt.Sprintf("%d", q), dstImagick)
} else {
cmd = exec.Command("convert", i.Filename, "-strip", "-resize", wh, dstImagick)
}
if err := cmd.Run(); err != nil {
return err
}
i.Width = w
i.Height = h
i.Type = format
if optimize {
i.optimize(dst)
}
return nil
}
示例9: graphviz
// Graphviz generates a specification for the graphviz program that visualizes the
// communication graph of a stitch.
func graphviz(outputFormat string, slug string, dot string) {
f, err := util.AppFs.Create(slug + ".dot")
if err != nil {
panic(err)
}
defer f.Close()
f.Write([]byte(dot))
if outputFormat == "graphviz" {
return
}
defer exec.Command("rm", slug+".dot").Run()
// Dependencies:
// - easy-graph (install Graph::Easy from cpan)
// - graphviz (install from your favorite package manager)
var writeGraph *exec.Cmd
switch outputFormat {
case "ascii":
writeGraph = exec.Command("graph-easy", "--input="+slug+".dot",
"--as_ascii")
case "pdf":
writeGraph = exec.Command("dot", "-Tpdf", "-o", slug+".pdf",
slug+".dot")
}
writeGraph.Stdout = os.Stdout
writeGraph.Stderr = os.Stderr
writeGraph.Run()
}
示例10: Run
func (command Command) Run() {
fmt.Printf("Initializing %s\n", command.Name)
if command.Before != nil {
command.Before()
}
args := strings.Split(command.Value, " ")
var cmd *exec.Cmd
if len(args) > 1 {
cmd = exec.Command(args[0], args[1:len(args)]...)
} else {
cmd = exec.Command(args[0])
}
err := cmd.Run()
if err != nil {
log.Fatal(err)
}
for _, subcommand := range command.SubCommands {
subcommand.Run()
}
fmt.Printf("Finished %s\n", command.Name)
}
示例11: GetDiff
func GetDiff(repoPath, commitid string) (*Diff, error) {
repo, err := git.OpenRepository(repoPath)
if err != nil {
return nil, err
}
commit, err := repo.GetCommit(commitid)
if err != nil {
return nil, err
}
rd, wr := io.Pipe()
var cmd *exec.Cmd
// First commit of repository.
if commit.ParentCount() == 0 {
cmd = exec.Command("git", "show", commitid)
} else {
c, _ := commit.Parent(0)
cmd = exec.Command("git", "diff", c.Id.String(), commitid)
}
cmd.Dir = repoPath
cmd.Stdout = wr
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
go func() {
cmd.Run()
wr.Close()
}()
defer rd.Close()
return ParsePatch(cmd, rd)
}
示例12: runAndLog
func runAndLog(cmd *exec.Cmd) (string, string, error) {
var stdout, stderr bytes.Buffer
log.Printf("Executing: %s %v", cmd.Path, cmd.Args[1:])
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
stdoutString := strings.TrimSpace(stdout.String())
stderrString := strings.TrimSpace(stderr.String())
if _, ok := err.(*exec.ExitError); ok {
message := stderrString
if message == "" {
message = stdoutString
}
err = fmt.Errorf("VMware error: %s", message)
}
log.Printf("stdout: %s", stdoutString)
log.Printf("stderr: %s", stderrString)
// Replace these for Windows, we only want to deal with Unix
// style line endings.
returnStdout := strings.Replace(stdout.String(), "\r\n", "\n", -1)
returnStderr := strings.Replace(stderr.String(), "\r\n", "\n", -1)
return returnStdout, returnStderr, err
}
示例13: install_vim
// requires dotfile path, home path
func install_vim(dp string, hp string) {
src1 := filepath.Join(dp, ".vim")
dst1 := filepath.Join(hp, ".vim")
symlink(src1, dst1)
src2 := filepath.Join(dp, ".vimrc")
dst2 := filepath.Join(hp, ".vimrc")
symlink(src2, dst2)
var gitcmd *exec.Cmd
_, err := os.Lstat(filepath.Join(dp, ".vim", "bundle", "vundle"))
if err == nil {
fmt.Printf("Skipping vundle clone because" +
" .vim/bundle/vundle exists")
goto vundle_init
}
if err.(*os.PathError).Err.Error() != "no such file or directory" {
panic(fmt.Sprintf("Failed to handle stat of"+
".vim/bundle/vundle %s.", err))
}
gitcmd = exec.Command("git", "clone",
"https://github.com/gmarik/vundle.git",
filepath.Join(dp, ".vim/bundle/vundle"))
err = gitcmd.Run()
if err != nil {
panic(fmt.Sprintf("Failed to clone vundle. %s", err))
}
vundle_init:
vcmd := exec.Command("vim", "+BundleInstall", "+qall")
err = vcmd.Run()
if err != nil {
panic(fmt.Sprintf("Failed to init vundle. %s", err))
}
}
示例14: GC
// GC enters the pod by fork/exec()ing the stage1's /gc similar to /init.
// /gc can expect to have its CWD set to the pod root.
// stage1Path is the path of the stage1 rootfs
func GC(pdir string, uuid *types.UUID, stage1Path string, debug bool) error {
err := unregisterPod(pdir, uuid)
if err != nil {
// Probably not worth abandoning the rest
log.Printf("Warning: could not unregister pod with metadata service: %v", err)
}
ep, err := getStage1Entrypoint(pdir, gcEntrypoint)
if err != nil {
return fmt.Errorf("error determining gc entrypoint: %v", err)
}
args := []string{filepath.Join(stage1Path, ep)}
if debug {
args = append(args, "--debug")
}
args = append(args, uuid.String())
c := exec.Cmd{
Path: args[0],
Args: args,
Stderr: os.Stderr,
Dir: pdir,
}
return c.Run()
}
示例15: run
func run(cmd *exec.Cmd) {
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
}