Trying to start an external editor from Go

I am trying to figure out how to start an external editor from Go, wait for the user to close the editor, and then continue to run the program. Based on this SO answer, I 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 the following:

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 also tried using exec.Run () instead of exec.Start (), but this does not seem to work (although it does not interrupt in the same place).

I can make it work if I use Gvim instead of Vim, but it refuses to work with both Vim and nano. I think this is due to the fact that Vim and nano work inside the terminal emulator instead of creating an external window.

+5
source share
3 answers

-, Stdin, Stdout Stderr Cmd os.Std(in | out | err). (, cmd):

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

# go-nut freenode.

+7

, ( ):

cmd := exec.Command("/usr/bin/xterm", "-e", "vim "+fpath)
+2

, cmd := exec.Command("vim", fpath), :

$ PATH= vim foo.txt
bash: vim: No such file or directory
$

Shell PATH, exec.Command - . vim exec.Command. exec.LookPath .

+1

All Articles