golang 调用 python,在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)?

解决方案

Use cmd.Start() and cmd.Wait() instead of 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)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值