使用 Go 例程连续将控制台日志打印到网页屏幕上



我让下面的go例程工作,但问题是它打印到控制台而不是屏幕。我的想法是在一个可以实时观看的网页上显示脚本中发生的命令或输出的运行日志。使用 FMT。Fprint不能做到这一点。发生的所有情况是我的网页永远不会完全加载。请帮忙?

在 Golang 中运行外部 python,捕获连续执行。命令标准输出

去代码

package main
import (
"log"
"net/http"
"time"
"os/exec"
"io"
"bufio"
"fmt"
"github.com/gorilla/mux"
)
func main() {
r := mux.NewRouter()
s := r.PathPrefix("/api/").Subrouter()
s.HandleFunc("/export", export).Methods("GET")
http.Handle("/", r)
log.Panic(http.ListenAndServe(":80", nil))
}
func export(w http.ResponseWriter, r *http.Request) {
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, w http.ResponseWriter) {
scanner := bufio.NewScanner(r)
for scanner.Scan() {
fmt.Fprint(w, scanner.Text()) //line I expect to print to the screen, but doesn't
}
}

蟒蛇脚本

import time
import sys
while True:
print "Hello"
sys.stdout.flush()
time.sleep(1)

该站点还有很多内容,因此我知道路由配置正确,因为当我不使用go例程时,打印到屏幕可以工作">

更新:

这是我的新更新函数,它打印到屏幕上,但仅在整个脚本运行后,而不是按原样打印

func export(w http.ResponseWriter, r *http.Request) {
cmd := exec.Command("python", "game.py")
cmd.Stdout = w
cmd.Start()
cmd.Wait()
}

我相信我可能仍然需要一个 go 例程才能让它在我走的时候打印出来,但是将 cmd.Start 和/或 cmd.Wait 放在一个中不起作用

更新:

因此,即使给出了所有内容,我也无法在运行时在浏览器上显示输出。它只是锁定浏览器,即使带有标题和刷新。我希望有时间对此给出一个完整的工作答案,但现在,上面的代码在运行后将代码正确打印到浏览器。我找到了一个我认为可能是我正在寻找的回购,也许它也会对遇到这个问题的其他人有所帮助。

https://github.com/yudai/gotty

这是一个非常基本(幼稚)的示例,但如何让您了解如何连续流式传输数据:

https://play.golang.org/p/vtXPEHSv-Sg

game.py的代码是:

import time
import sys
while True:
print("Hello")
sys.stdout.flush()
time.sleep(1)

网络应用代码:

package main
import (
"bufio"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"github.com/nbari/violetear"
)
func stream(w http.ResponseWriter, r *http.Request) {
cmd := exec.Command("python", "game.py")
rPipe, wPipe, err := os.Pipe()
if err != nil {
log.Fatal(err)
}
cmd.Stdout = wPipe
cmd.Stderr = wPipe
if err := cmd.Start(); err != nil {
log.Fatal(err)
}
go writeOutput(w, rPipe)
cmd.Wait()
wPipe.Close()
}
func writeOutput(w http.ResponseWriter, input io.ReadCloser) {
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming not supported", http.StatusInternalServerError)
return
}
// Important to make it work in browsers
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
in := bufio.NewScanner(input)
for in.Scan() {
fmt.Fprintf(w, "data: %sn", in.Text())
flusher.Flush()
}
input.Close()
}
func main() {
router := violetear.New()
router.HandleFunc("/", stream, "GET")
log.Fatal(http.ListenAndServe(":8080", router))
}

这里的关键部分是http的使用。刷新器和一些标头,使其在浏览器中工作:

w.Header().Set("Content-Type", "text/event-stream")

请注意,此代码的问题在于,一旦请求到达,它将exec永远循环的命令,因此永远不会调用wPipe.Close()

cmd.Wait()
wPipe.Close()

为了更详细,您可以在浏览器旁边的终端上打印输出:

for in.Scan() {
data := in.Text()
log.Printf("data: %sn", data)
fmt.Fprintf(w, "data: %sn", data)
flusher.Flush()
}

如果您有多个请求,您会注意到它会在终端中写入得更快,还不错,但您还会注意到,如果客户端关闭了连接/浏览器,您仍然会看到数据流出。

更好的方法是在上下文中执行命令,例如:https://golang.org/pkg/os/exec/#CommandContext

ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
if err := exec.CommandContext(ctx, "sleep", "5").Run(); err != nil {
// This will fail after 100 milliseconds. The 5 second sleep
// will be interrupted.
}

还要看看上下文 (https://stackoverflow.com/a/44146619/1135424) 不替换http.CloseNotifier因此,一旦客户端关闭浏览器,disconetcs 就会终止进程。

最后取决于您的需求,但希望可以让您了解如何使用http.Flusher界面以简单的方式流式传输数据。

只是为了好玩,这里有一个使用上下文的示例:

https://play.golang.org/p/V69BuDUceBA

仍然非常基本,但在这种情况下,如果客户端关闭浏览器,程序也会终止,因为练习可以很好地改进它并共享;-),请注意 CommandContext 的使用并ctx.Done()

package main
import (
"bufio"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"github.com/nbari/violetear"
)
func stream(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ch := make(chan struct{})
cmd := exec.CommandContext(ctx, "python", "game.py")
rPipe, wPipe, err := os.Pipe()
if err != nil {
log.Fatal(err)
}
cmd.Stdout = wPipe
cmd.Stderr = wPipe
if err := cmd.Start(); err != nil {
log.Fatal(err)
}
go writeOutput(w, rPipe)
go func(ch chan struct{}) {
cmd.Wait()
wPipe.Close()
ch <- struct{}{}
}(ch)
select {
case <-ch:
case <-ctx.Done():
err := ctx.Err()
log.Printf("Client disconnected: %sn", err)
}
}
func writeOutput(w http.ResponseWriter, input io.ReadCloser) {
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming not supported", http.StatusInternalServerError)
return
}
// Important to make it work in browsers
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
in := bufio.NewScanner(input)
for in.Scan() {
data := in.Text()
log.Printf("data: %sn", data)
fmt.Fprintf(w, "data: %sn", data)
flusher.Flush()
}
input.Close()
}
func main() {
router := violetear.New()
router.HandleFunc("/", stream, "GET")
log.Fatal(http.ListenAndServe(":8080", router))
}

最新更新