【问题标题】:Using exec only starts program in background使用 exec 仅在后台启动程序
【发布时间】:2018-08-05 13:53:33
【问题描述】:

我正在尝试制作一个通过命令行调用另一个程序(带有 GUI)的 go 程序。

使用 os/exec 包。外部程序启动,但始终在后台运行。 (即使我尝试启动“Notepad.exe”或随后调用实际程序的 .bat 文件。)

在任务管理器中你可以看到进程但是没有办法与之交互。

这是我一直在试验的代码示例:

cmd := exec.Command("cmd.exe", "/C", "start", "\"\"", `Notepad.exe`)

log.Println("cmd.exe", "/C", "start", "\"\"", `Notepad.exe`)

cmd.Stdout = os.Stdout
if err := cmd.Start(); err != nil {
    log.Println("Error: ", err)
}

有没有办法更改代码,使其以可以通过 UI 交互的方式启动“Notepad.exe”?

我正在尝试使用 Mac 上编译的 Windows 程序。

【问题讨论】:

    标签: go exec


    【解决方案1】:

    您不需要那个空的"" 参数,只需使用:

    cmd := exec.Command("cmd.exe", "/C", "start", "notepad.exe")
    

    另外notepad.exe 不会向其标准输出写入任何内容,因此您无需设置它。只需像这样运行它:

    s := []string{"cmd.exe", "/C", "start", "notepad.exe"}
    log.Println("Starting", s)
    
    cmd := exec.Command(s[0], s[1:]...)
    if err := cmd.Run(); err != nil {
        log.Println("Error:", err)
    }
    

    【讨论】:

    • 我发现代码本身运行良好。我认为问题出在我的代码中,它用这部分调用了函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多