Home > Software engineering >  Spawn vim using golang
Spawn vim using golang

Time:11-25

I am trying to run a simple program that spawns a vim process.

The user should be able (when the exec.Command starts) to switch to vim window and the process execution should halt there.

When user closes vim (wq!) the program execution should resume from that point.

The following simple attempt fails but I cannot figure out why

package main

import (
    "log"
    "os/exec"
)

func main() {

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

    err := cmd.Run()

    if err != nil {
        log.Fatal(err)
    }
}
▶ go run main.go
2022/11/25 09:16:44 exit status 1
exit status 1

Why the exit status 1?

CodePudding user response:

You missed these two lines:

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

Thanks to these two lines the user is able to edit with vim the file in the terminal. The control is returned to the program when the user quit from the terminal (e.g., with the command :wq). Below, you can find the whole code:

package main

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

func main() {
    cmd := exec.Command("vim", "lala")

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

    err := cmd.Run()
    if err != nil {
        log.Fatal(err)
    }
}

Hope this helps!

CodePudding user response:

Because you should set Stdin and Stdoutfor cmd:

package main

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

func main() {

    cmd := exec.Command("vim", "lala")
    cmd.Stdin = os.Stdin
    cmd.Stdout = os.Stdout
    err := cmd.Run()

    if err != nil {
        log.Fatal(err)
    }
}
  • Related