英文:
Launching a new command window from Golang in Windows
问题
我正在编写一个使用命令窗口(CMD)进行用户输入和输出的Go应用程序。我需要启动另一个使用自己窗口的应用程序实例。
我尝试使用"os/exec"包,但它只能为GUI应用程序创建窗口。我尝试使用cmd /c ___
来执行应用程序,但它仍然没有创建一个单独的窗口。
有没有办法启动一个具有自己窗口、标准输入和标准输出的非GUI应用程序?
英文:
I'm writing a go application that just uses the command window (CMD) for user input and output. I need to launch another instance of the application that is using its own window.
I trying to use the "os/exec" package but that only creates a window for GUI apps. I tried executing the application with cmd /c ___
but it still hasn't created a separate window.
Is there a way to launch a non-GUI application with its own window, stdin and stdout?
答案1
得分: 14
我找到了!
关键是在 cmd /c
后面使用 "start" 作为命令。
以下是代码:
cmd := exec.Command("cmd", "/C", "start", _path_to_executable_)
err := cmd.Start()
希望对你有帮助!
英文:
I found it!
The trick is to use the "start" as a command after cmd /c
Here's the code:
cmd:= exec.Command("cmd","/C","start",_path_to_executable_)
err=cmd.Start()
答案2
得分: 0
没有中间人cmd
,也可以通过修改进程创建标志来实现:
import (
"log"
"os/exec"
"syscall"
)
const (
CREATE_NEW_CONSOLE = 0x10
)
func main() {
cmd := exec.Cmd{Path: "c:\\windows\\system32\\wsl.exe",
Args: []string{"-e", "sudo", "aptitude"},
SysProcAttr: &syscall.SysProcAttr{
CreationFlags: CREATE_NEW_CONSOLE,
NoInheritHandles: true,
},
}
err := cmd.Run()
log.Print(err)
}
NoInheritHandles
允许窗口拥有自己的标准输入和标准输出。
英文:
Without an intermediary cmd
, it's also possible by modifying the process creation flags:
import (
"log"
"os/exec"
"syscall"
)
const (
CREATE_NEW_CONSOLE = 0x10
)
func main() {
cmd := exec.Cmd{Path: "c:\\windows\\system32\\wsl.exe",
Args: []string{"-e", "sudo", "aptitude"},
SysProcAttr: &syscall.SysProcAttr{
CreationFlags: CREATE_NEW_CONSOLE,
NoInheritHandles: true,
},
}
err := cmd.Run()
log.Print(err)
}
NoInheritHandles
lets the window have its own stdin and stdout.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论