Golang为CMD执行cd命令 [英] Golang execute cd command for CMD

查看:883
本文介绍了Golang为CMD执行cd命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用golang和exec库去某个路径c:\并运行一个.exe文件。



当我运行我的go代码给了我:



exec:cd:/:文件不存在

解决方案

cd 命令是shell的内置命令,无论是bash,cmd.exe,PowerShell还是其他。您不会执行 cd 命令,然后执行您要运行的程序。相反,您要将要运行的 Dir Cmd 设置为包含该程序的目录:

  package main 

import(
fmt
log
os / exec


func main(){
cmd:= exec.Command(program)//或者任何程序是
cmd.Dir =C:/ usr / bin//或者任何它在
中的目录,err:= cmd.Output()
如果err!= nil {
log.Fatal(err)
} else {
fmt.Printf(%s,out);
}
}

请参阅 Cmd文档了解更多信息。或者,您可以在运行程序之前使用 os / Chdir 更改工作目录。


I want to use golang and exec library to go to a certain path "c:\" and run a .exe file.

when i run my go code it gives me:

exec: "cd:/": file does not exist

解决方案

The cd command is a builtin of your shell, whether bash, cmd.exe, PowerShell, or otherwise. You would not exec a cd command and then exec the program you want to run. Instead, you want to set the Dir of the Cmd you're going to run to the directory containing the program:

package main

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

func main() {
    cmd := exec.Command("program") // or whatever the program is
    cmd.Dir = "C:/usr/bin"         // or whatever directory it's in
    out, err := cmd.Output()
    if err != nil {
        log.Fatal(err)
    } else {
        fmt.Printf("%s", out);
    }
}

See the Cmd documentation for more information. Alternatively, you could use os/Chdir to change the working directory before running the program.

这篇关于Golang为CMD执行cd命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆