douxianwu2221 2012-08-23 08:57
浏览 49
已采纳

尝试从Go程序中启动外部编辑器

I am trying to figure out how to launch an external editor from within a Go program, wait for the user to close the editor, and then continue execution of the program. Based on this SO answer, I currently have this code:

package main

import (
    "log"
    "os"
    "os/exec"
)

func main() {
    fpath := os.TempDir() + "/thetemporaryfile.txt"
    f, err := os.Create(fpath)
    if err != nil {
        log.Printf("1")
        log.Fatal(err)
    }
    f.Close()

    cmd := exec.Command("vim", fpath)
    err = cmd.Start()
    if err != nil {
        log.Printf("2")
        log.Fatal(err)
    }
    err = cmd.Wait()
    if err != nil {
        log.Printf("Error while editing. Error: %v
", err)
    } else {
        log.Printf("Successfully edited.")
    }

}

When I run the program, I get this:

chris@DPC3:~/code/go/src/launcheditor$ go run launcheditor.go 
2012/08/23 10:50:37 Error while editing. Error: exit status 1
chris@DPC3:~/code/go/src/launcheditor$ 

I have also tried using exec.Run() instead of exec.Start(), but that doesn't seem to work either (though it doesn't fail at the same place).

I can get it to work if I use Gvim instead of Vim, but it refuses to work with both Vim and nano. I think it's related to Vim and nano running inside the terminal emulator instead of creating an external window.

  • 写回答

3条回答 默认 最新

  • dqczgtem06898 2012-08-23 10:51
    关注

    Apparently, you have to set Stdin, Stdout and Stderr on the Cmd object to os.Std(in|out|err). Like this (assuming that the object is called cmd):

    cmd.Stdin = os.Stdin
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    

    Credit for solving this goes to the guys on #go-nuts on freenode.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用