dongqie2010 2018-07-05 10:23
浏览 178
已采纳

在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?

  • 写回答

1条回答 默认 最新

  • doz59484 2018-07-05 11:06
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启