dopmgo4707 2015-05-07 08:36
浏览 28
已采纳

os.exec.Command和pbcopy

I am trying to execute bash command "hello world" | /usr/bin/pbcopy inside go:

package main

import (
    "fmt"
    "os/exec"
    "strings"
)

func Cmd(cmd string) {
    fmt.Println("command is ", cmd)
    parts := strings.Fields(cmd)
    head := parts[0]
    parts = parts[1:len(parts)]
    out, err := exec.Command(head, parts...).Output()
    if err != nil {
        fmt.Printf("%s", err)
    }
    fmt.Println("out")
    fmt.Println(string(out))
}

func main() {
    Cmd(`echo "hello world" | /usr/bin/pbcopy`)
}

When I run this go file, it outputs:

command is  echo "hello world" | /usr/bin/pbcopy
out
"hello world" | /usr/bin/pbcopy

I expect clipboard to be equal to "hello world" but it is not.

Update

I've tried to use io.Pipe

package main

import (
    "bytes"
    "io"
    "os"
    "os/exec"
)

func main() {
    c1 := exec.Command(`echo "hello world"`)
    c2 := exec.Command("/usr/bin/pbcopy")

    r, w := io.Pipe()
    c1.Stdout = w
    c2.Stdin = r

    var b2 bytes.Buffer

    c2.Stdout = &b2

    c1.Start()
    c2.Start()
    c1.Wait()
    w.Close()
    c2.Wait()
    io.Copy(os.Stdout, &b2)
}

... but clipboard is still not equal to "hello world"

  • 写回答

1条回答 默认 最新

  • drv16759 2015-05-08 00:35
    关注

    Command takes an executable and a list of arguments. So when you call

    exec.Command(`echo "hello world"`)
    

    That literally tries to run a command called echo "hello world" (with space and quotes). As you've already learned, exec.Command does not pass things to the shell, so "|" won't work either this way. So if you're going to piece it all together by tying the stdout and stdin together, it would look like this:

    func main() {
        c1 := exec.Command("echo", "hello world")
        c2 := exec.Command("/usr/bin/pbcopy")
    
        c1stdout, _ := c1.StdoutPipe()
        c2stdin, _ := c2.StdinPipe()
    
        c1.Start()
        c2.Start()
    
        io.Copy(c2stdin, c1stdout)
    
        c2stdin.Close()
        c2.Wait()
    }
    

    But there's no need for all that. You have a shell. It can do all of this for you if you ask it to.

    func main() {
        exec.Command("sh", "-c", `echo "hello world" | pbcopy`).Run()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 MATLAB动图的问题
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名