英文:
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
设置Stdin
和Stdout
:
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 Stdout
for 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)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论