简体   繁体   English

怎么从去开始vim?

[英]How to start vim from go?

I've got a command line tool written in Golang and I need to start vim from it. 我有一个用Golang编写的命令行工具,我需要从它启动vim。 However it's not working, and there's not any error or much else to work with. 然而,它不起作用,并没有任何错误或其他许多工作。 I've reduced the code to just this: 我已经将代码简化为:

package main

import (
    "fmt"
    "os/exec"
)

func main() {
    cmd := exec.Command("vim", "test.txt")
    err := cmd.Run()
    fmt.Println(err)
}

When I run this, I can see the vim process for a 2-3 seconds but the application doesn't actually open. 当我运行它时,我可以看到vim进程2-3秒,但应用程序实际上没有打开。 Then the program simply exits (and the vim process closes) with an "exit status 1". 然后程序简单退出(并且vim进程关闭),退出状态为1。

I've also tried this to capture stderr: 我也尝试过捕获stderr:

package main

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

func main() {
    cmd := exec.Command("vim", "test.txt")
    var stderr bytes.Buffer
    cmd.Stderr = &stderr
    err := cmd.Run()
    fmt.Println(err)
    fmt.Println(stderr)
}

But in this case, the program gets stuck indefinitely. 但在这种情况下,程序会无限期地陷入困境。

Any idea what could be the issue? 知道可能是什么问题吗?

Pass on stdin and stdout from the calling program which, provided it was run from a terminal (likely for a command line program) will start vim for you and return control when the user has finished editing the file. 从调用程序传递stdinstdout ,只要它从终端(可能是命令行程序)运行,它将为您启动vim并在用户编辑完文件后返回控制。

package main

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

func main() {
    cmd := exec.Command("vim", "test.txt")
    cmd.Stdin = os.Stdin
    cmd.Stdout = os.Stdout
    err := cmd.Run()
    fmt.Println(err)
}

VIM needs a proper terminal and detects the absence of one. VIM需要一个合适的终端,并检测到没有终端。

If you use the StderrPipe and read it while vim is running you will see this: 如果您使用StderrPipe并在vim运行时读取它,您将看到:

2014/02/02 20:25:49 Vim: Warning: Output is not to a terminal
2014/02/02 20:25:49 Vim: Warning: Input is not from a terminal

Example for reading stderr while executing ( on play ): 执行( 正在播放 )时读取stderr的示例:

func logger(pipe io.ReadCloser) {
    reader := bufio.NewReader(pipe)

    for {
        output, err := reader.ReadString('\n')

        if err != nil {
            log.Println(err)
            return
        }

        log.Print(string(output))
    }
}

pipe, err := cmd.StderrPipe()

go logger(pipe)
cmd.Run()

For vim to run you probably need to emulate a terminal. 要让vim运行,您可能需要模拟终端。

Maybe goat ( doc ) can help you out: 也许山羊doc )可以帮助你:

tty := term.NewTTY(os.Stdin)

cmd := exec.Command("vim", "test.txt")
cmd.Stdin = t
cmd.Stdout = t

// ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM