在围棋,我该如何捕获标准输出的函数转换成字符串?在围棋,我该如何捕获标准输出的函数转换成字符串?(I

2019-05-13 21:49发布

在Python中,例如,我可以做到以下几点:

realout = sys.stdout
sys.stdout = StringIO.StringIO()
some_function() # prints to stdout get captured in the StringIO object
result = sys.stdout.getvalue()
sys.stdout = realout

你可以在去这样做吗?

Answer 1:

我同意你应该使用fmt.Fprint功能,如果你能管理它。 但是,如果你不控制其输出你捕捉的代码,你可能不会有这样的选择。

穆斯塔法的答案的工作,但如果你想这样做没有一个临时文件,你可以使用os.Pipe 。 下面是这相当于穆斯塔法与围棋的测试包启发一些代码的例子。

package main

import (
    "bytes"
    "fmt"
    "io"
    "os"
)

func print() {
    fmt.Println("output")
}

func main() {
    old := os.Stdout // keep backup of the real stdout
    r, w, _ := os.Pipe()
    os.Stdout = w

    print()

    outC := make(chan string)
    // copy the output in a separate goroutine so printing can't block indefinitely
    go func() {
        var buf bytes.Buffer
        io.Copy(&buf, r)
        outC <- buf.String()
    }()

    // back to normal state
    w.Close()
    os.Stdout = old // restoring the real stdout
    out := <-outC

    // reading our temp stdout
    fmt.Println("previous output:")
    fmt.Print(out)
}


Answer 2:

我不建议这样做,但你可以改变实现它os.Stdout 。 由于此变量的类型的os.File ,临时输出也应该是一个文件。

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "path/filepath"
)

func print() {
    fmt.Println("output")
}

func main() {
    // setting stdout to a file
    fname := filepath.Join(os.TempDir(), "stdout")
    fmt.Println("stdout is now set to", fname)
    old := os.Stdout // keep backup of the real stdout
    temp, _ := os.Create(fname) // create temp file
    os.Stdout = temp

    print()

    // back to normal state
    temp.Close()
    os.Stdout = old // restoring the real stdout

    // reading our temp stdout
    fmt.Println("previous output:")
    out, _ := ioutil.ReadFile(fname)
    fmt.Print(string(out))
}

我不建议,因为这是太多的黑客,而不是走得很地道。 我建议传递一个io.Writer的功能和写入到输出到。 这是更好的方式做几乎同样的事情。

package main

import (
    "bytes"
    "fmt"
    "io"
    "os"
)

func print(w io.Writer) {
    fmt.Fprintln(w, "output")
}

func main() {
    fmt.Println("print with byes.Buffer:")
    var b bytes.Buffer
    print(&b)
    fmt.Print(b.String())

    fmt.Println("print with os.Stdout:")
    print(os.Stdout)
}


Answer 3:

这个答案是类似于以前的,但看起来使用IO / ioutil清洁。

http://play.golang.org/p/fXpK0ZhXXf

package main

import (
  "fmt"
  "io/ioutil"
  "os"
)

func main() {
  rescueStdout := os.Stdout
  r, w, _ := os.Pipe()
  os.Stdout = w

  fmt.Println("Hello, playground") // this gets captured

  w.Close()
  out, _ := ioutil.ReadAll(r)
  os.Stdout = rescueStdout

  fmt.Printf("Captured: %s", out) // prints: Captured: Hello, playground
}


Answer 4:

我觉得整个想法是不可取的(竞争状态)所有,但我想用一个os.Stdout可以胡来的方式类似于/类比到你的榜样。



文章来源: In Go, how do I capture stdout of a function into a string?
标签: go stdout