1

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\n", line)
        f.Close()
    }
}

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.