在Windows中使用Golang启动一个新的命令窗口。

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

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.

huangapple
  • 本文由 发表于 2015年5月12日 13:31:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/30182508.html
匿名

发表评论

匿名网友

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

确定