尝试从Go程序中启动外部编辑器 [英] Trying to launch an external editor from within a Go program
问题描述
我试图弄清楚如何从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\n", 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$
我也尝试使用 exec.Run()
代替 exec.Start()
,但这似乎也不起作用(尽管它不起作用)在同一个地方失败).
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).
如果我使用Gvim而不是Vim,我可以使它工作,但是它拒绝与Vim和nano一起工作.我认为这与在终端仿真器中运行而不是创建外部窗口的Vim和nano有关.
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.
推荐答案
显然,您必须在 Stdin
, Stdout
和 Stderr
上设置 os.Std(in | out | err)
的 Cmd
对象.像这样(假设对象称为 cmd
):
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
解决这个问题的信用归于freenode上#go-nuts上的家伙.
Credit for solving this goes to the guys on #go-nuts on freenode.
这篇关于尝试从Go程序中启动外部编辑器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!