dongtaochan0777 2017-01-01 12:09
浏览 330
已采纳

在Golang中运行外部python,捕获连续的exec.Command Stdout

So my go script will call an external python like this

cmd = exec.Command("python","game.py")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
go func(){
    err := cmd.Run()
    if err != nil{
    panic(err)
    }
}()

It runs my python script concurrently which is awesome. But now the problem is, my python script will run infinitely and it will print out some information from time to time. I want to "catch" these Stdout and print them out on my golang terminal. How do I do it concurrently (without waiting my python script to exit)?

  • 写回答

1条回答 默认 最新

  • dt1888 2017-01-01 12:29
    关注

    Use cmd.Start() and cmd.Wait() instead of cmd.Run().

    https://golang.org/pkg/os/exec/#Cmd.Run

    Run starts the specified command and waits for it to complete.

    Start starts the specified command but does not wait for it to complete.

    Wait waits for the command to exit. It must have been started by Start.

    And if you want to capture stdout/stderr concurrently, use cmd.StdoutPipe() / cmd.StderrPipe() and read it by bufio.NewScanner()

    package main
    
    import (
        "bufio"
        "fmt"
        "io"
        "os/exec"
    )
    
    func main() {
        cmd := exec.Command("python", "game.py")
        stdout, err := cmd.StdoutPipe()
        if err != nil {
            panic(err)
        }
        stderr, err := cmd.StderrPipe()
        if err != nil {
            panic(err)
        }
        err = cmd.Start()
        if err != nil {
            panic(err)
        }
    
        go copyOutput(stdout)
        go copyOutput(stderr)
        cmd.Wait()
    }
    
    func copyOutput(r io.Reader) {
        scanner := bufio.NewScanner(r)
        for scanner.Scan() {
            fmt.Println(scanner.Text())
        }
    }
    

    The following is a sample python code for reproducing real-time output. The stdout may be buffered in Python. Explicit flush may be required.

    import time
    import sys
    
    while True:
        print "Hello"
        sys.stdout.flush()
        time.sleep(1)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题