英文:
How do I open a file with a text editor in Go?
问题
我正在开发一个命令行工具,可以轻松创建文件,并在某个标志为 true 时打开它。这是我看到的在文本编辑器中打开文件的唯一方法:
cmd := exec.Command(file)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Start()
if err != nil {
fmt.Printf("Start failed: %s", err)
}
fmt.Printf("Waiting for command to finish.\n")
err = cmd.Wait()
fmt.Printf("Command finished with error: %v\n", err)
顺便说一下,我并不真正理解这段代码,并且遇到了以下错误:
Start failed: fork/exec H:/code/txt_projects/hello6.txt: %1 is not a valid Win32 application.Waiting for command to finish.
Command finished with error: exec: not started
如何修复这个问题?例如,如何使用记事本打开文件?
英文:
I'm working on an CLI tool that lets you create files easily and opens it if a certain flag is true. This is the only way of opening a file in a text editor that I saw:
cmd := exec.Command(file)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Start()
if err != nil {
fmt.Printf("Start failed: %s", err)
}
fmt.Printf("Waiting for command to finish.\n")
err = cmd.Wait()
fmt.Printf("Command finished with error: %v\n", err)
...which I don't really understand by the way, and got the following error:
Start failed: fork/exec H:/code/txt_projects/hello6.txt: %1 is not a valid Win32 application.Waiting for command to finish.
Command finished with error: exec: not started
How do I fix this? How can I open the file with, for example, Notepad?
答案1
得分: 2
你应该在一个字符串上调用exec.Command
,该字符串的内容是可执行命令的路径,其他参数作为该命令的参数,例如:
// 快捷方式为环境变量中的命令
//exepath := "notepad"
exepath := "C:\\Windows\\system32\\notepad.exe"
file := "H:\\code\\txt_projects\\hello6.txt"
cmd := exec.Command(exepath, file)
请参考文档。
英文:
You should call exec.Command
on a string whose content is a executable command path, with some arguments for this command as other parameters, like:
// shortcut for command in ENV PATH
//exepath := "notepad"
exepath := "C:\\Windows\\system32\\notepad.exe"
file := "H:\\code\\txt_projects\\hello6.txt"
cmd := exec.Command(exepath, file)
Refer to document.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论