Spawn vim using golang

huangapple go评论85阅读模式
英文:

Spawn vim using golang

问题

我正在尝试运行一个简单的程序,它会生成一个vim进程。

exec.Command开始时,用户应该能够切换到vim窗口,并且进程执行应该在那里暂停。

当用户关闭vim(使用wq!)后,程序执行应该从那个点继续。

下面的简单尝试失败了,但我无法弄清楚为什么

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

为什么会出现exit status 1

英文:

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?

答案1

得分: 2

你错过了这两行代码:

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

由于这两行代码,用户可以在终端中使用vim编辑文件。当用户从终端退出(例如,使用命令:wq)时,控制权将返回给程序。下面是完整的代码:

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)
	}
}

希望对你有所帮助!

英文:

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!

答案2

得分: 0

因为你应该为cmd设置StdinStdout

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)
	}
}
英文:

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)
	}
}

huangapple
  • 本文由 发表于 2022年11月25日 15:19:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/74569391.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定