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()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本