doulu1867 2018-04-03 16:47
浏览 1111

一旦在golang中准备好从stdout管道读取

I'm facing with a weird golang issue. The following code will clarify:

package main

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

var (
    pw io.WriteCloser
    pr io.ReadCloser
)

func main() {
    term := exec.Command("/bin/sh")

    // Get stdin writer pipe
    pw, _ = term.StdinPipe()
    pr, _ = term.StdoutPipe()

    term.Start()

    run("cd ~")
    pwd := run("pwd");

    // Do something with pwd output
    ...

    term.Wait()
}

func run(c string) string {
    io.WriteString(pw, fmt.Sprintln(c))

    buf := make([]byte, 32 * 1024)
    pr.Read(buf)
    return string(buf)
}

I'd like to run some commands in a shell env and read their output. There's no problem on write/run command but it seems that there're some limitations while reading:

  • you can't know if a command doesn't output anything or not;
  • there's no way to check if stdout is ready to be read or not.

The pr.Read(dest) method will block the code flow until something is read from stdout. As said, the goal is to read sequentially (without using a go routine and/or an infinite loop). This means that if we send a cd command the func end is never reached.

Setting the non-block flag through unix.SetNonblock on stdout file descriptor seems to solve the above issue but you can't know prior if it's ready or not and an error saying "resource temporary not available" is returned from .Read call.

  • 写回答

1条回答 默认 最新

  • doutao5499 2018-04-04 12:02
    关注

    As Cerise Limón mentioned go functions whould be the way to go here, since these sorts of interactive scripting exercises are traditionally done with expect.

    You can wrap the the parrellel execution into a library to it might still look like sequencial code, so this might be helpful: https://github.com/ThomasRooney/gexpect

    From the readme:

    child, err := gexpect.Spawn("python")
    if err != nil { panic(err) }
    child.Expect(">>>")
    child.SendLine("print 'Hello World'")
    child.Interact()
    child.Close()
    
    评论

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP