dqp21271 2015-01-19 09:36
浏览 289
已采纳

golang监视器cmd输出

I want to monitor a process status. The task is almost like this. t.py just outputs a number every second and I want to use test.go to store this number into a file. Unfortunately, the following code cannot do the job.

t.py:

import time
from sys import stdout

i=0
while 1:
    print("%d" % i) 
    time.sleep(1)
    i += 1

test.go

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

func main() {
    cmd := exec.Command("python", "t.py")
    stdout, err := cmd.StdoutPipe()
    if err != nil {
        fmt.Println(err)
    }
    scanner := bufio.NewScanner(stdout)
    err = cmd.Start()
    if err != nil {
        fmt.Println(err)
    }
    for scanner.Scan() {
        line := scanner.Text()
        f, _ := os.Create("./temp.txt")
        fmt.Fprintf(f, "then %s
", line)
        f.Close()
    }
}
  • 写回答

1条回答 默认 最新

  • dongxu0690 2015-01-19 10:00
    关注

    Output is buffered. Add stdout.flush() after print

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

报告相同问题?