在Go代码中无法调用`vim`。

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

Can not call `vim` within go code

问题

我试图在Go程序中调用vim,代码类似于这样:

package main

import (
    "fmt"
    "os"
    "os/exec"
)

func main() {
    err := exec.Command("vim", "a.txt").Run()
    if err != nil {
        fmt.Println(err)
    }
    os.Exit(0)
}

我运行了go run mycode.go然后得到了:

exit status 1

我尝试了几种方法来成功实现这个,例如用Start()Output()等替换Run(),但似乎都不起作用。最后,我想做的是调用vim并停止当前的Go程序。我只想看到vim出现,仅此而已。

英文:

I try to call vim within go program, which code similar to this:

package main

import (
        "fmt"
        "os"
        "os/exec"
)

func main() {
        err := exec.Command("vim", "a.txt").Run()
        if err != nil {
                fmt.Println(err)
        }
        os.Exit(0)
}

I ran go run mycode.go then got:

exit status 1

I have tried several ways to succeed this e.g. replace Run() by Start(), Output(), ..., but it seems not work. Finally, What I try to do is I try to call vim and stop my current go program. I just want to see vim appear, that's all.

答案1

得分: 7

为了使vim能够渲染其界面,您需要将标准输入/输出流附加到进程中:

package main

import (
        "fmt"
        "os"
        "os/exec"
)

func main() {
        cmd := exec.Command("vim", "a.txt")
        cmd.Stdin = os.Stdin
        cmd.Stdout = os.Stdout
        cmd.Stderr = os.Stderr
        err := cmd.Run()
        if err != nil {
                fmt.Println(err)
        }
        os.Exit(0)
}

不附加流类似于从shell中运行以下命令:

vim < /dev/null > /dev/null 2> /dev/null
英文:

In order for vim to render its interface, you need to attach the standard input/output streams to the process:

package main

import (
        &quot;fmt&quot;
        &quot;os&quot;
        &quot;os/exec&quot;
)

func main() {
        cmd := exec.Command(&quot;vim&quot;, &quot;a.txt&quot;)
        cmd.Stdin = os.Stdin
        cmd.Stdout = os.Stdout
        cmd.Stderr = os.Stderr
        err := cmd.Run()
        if err != nil {
                fmt.Println(err)
        }
        os.Exit(0)
}

Not attaching the streams is similar to running the following command from your shell:

vim &lt; /dev/null &gt; /dev/null 2&gt; /dev/null

huangapple
  • 本文由 发表于 2016年1月12日 21:11:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/34744648.html
匿名

发表评论

匿名网友

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

确定