在Go中运行Python命令
I am trying following code:
package main
import ("fmt"; "log"; "os/exec")
func main() {
cmd := exec.Command("/usr/bin/python3.5", "-c",
"import easygui as eg; print('Hello world'); eg.msgbox(msg='Hi there'); print('from Golang')")
out, err := cmd.CombinedOutput()
if err != nil { log.Fatal(err) }
fmt.Printf(string(out)) }
I am trying it to print on terminal first, then show a gui messagebox, then again print on terminal.
However, it first shows a message box, then does both print statements.
How can this be solved?
我正在尝试以下代码: p>
package main
import (“ fmt”;“ log”;“ os / exec”)
func main(){
cmd:= exec.Command(“ / usr / bin / python3.5”,“ -c”,
“ import easygui例如; print('Hello world'); eg.msgbox(msg ='Hi there'); print('from Golang')“)
out,err:= cmd.CombinedOutput()
if err! = nil {log.Fatal(err)}
fmt.Printf(string(out))}
code> pre>
我尝试先在终端上打印,然后 显示gui消息框,然后再次在终端上打印。 p>
但是,它首先显示一个消息框,然后同时显示两个打印语句。 p>
如何解决? p>
Your program runs cmd.CombinedOutput()
, which launches the Python script (as a side effect displaying the message box) and collects its stdout into a variable; then does a single fmt.Printf
to print out the program's output. That leads to the sequencing you're seeing.
If you call cmd.StdoutPipe()
then you will get an io.Reader
that has the script's stdout instead. It's your responsibility to read from the pipe and copy to your own process's stdout; the os/exec documentation has an example. You need to cmd.Start()
, then read everything from the pipe, then cmd.Wait()
to clean up after yourself.
You may also be able to directly assign cmd.Stdout = os.Stdout
, then cmd.Run()
. In this case you won't be able to see the output within your program, but you also won't have to copy it around.