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

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()
    }
}

图片转代码服务由CSDN问答提供 功能建议

我要监视进程状态。 任务几乎是这样的。 t.py只是每秒输出一个数字,我想使用test.go将该数字存储到文件中。 不幸的是,以下代码无法完成这项工作。

t.py:

 导入时间
从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(){\  n cmd:= exec.Command(“ python”,“ t.py”)
 stdout,err:= cmd.StdoutPipe()
如果err!= nil {
 fmt.Println(err)
} \  n扫描仪:= bufio.NewScanner(stdout)
 err = cmd.Start()
如果err!= nil {
 fmt.Println(err)
} 
 for扫描仪.Scan(){
行 := 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
    
    点赞 打赏 评论

相关推荐 更多相似问题