英文:
How to copy a file from one directory to another using "os/exec" package in GO
问题
如果我在目录A中运行GO代码,并且需要将文件从目录B复制到目录C,应该如何操作?我尝试添加cmd.Dir = "B",但它只能复制目录B中的文件,当我尝试使用目录C的完整路径时,它会抛出错误"exit status 1"。
基本代码示例:
当前位于目录A,位置为"/var/A"
cmd := exec.Command("cp","/var/C/c.txt","/var/B/")
err := cmd.Run()
英文:
if I am in directory A and running the GO code, and I need to copy a file from directory B to directory C , how to do it? I tried adding cmd.Dir = "B" but it can copy the files in "B" directory, but when I try full path for directory "C" it throws error "exit status 1"
basic code sample
Currently in directory A with location "/var/A"
cmd := exec.Command("cp","/var/C/c.txt","/var/B/")
err := cmd.Run()
答案1
得分: 2
"os/exec" 是用于运行外部程序的 Go 包,其中包括 Linux 实用程序。
// 命令名称是第一个参数,后续参数是命令的参数。
cmd := exec.Command("tr", "a-z", "A-Z")
// 提供一个 io.Reader 作为标准输入(可选)
cmd.Stdin = strings.NewReader("some input")
// 还有一个用于标准输出的写入器(也是可选的)
var out bytes.Buffer
cmd.Stdout = &out
// 运行命令并等待其完成(还有其他方法可以在不等待的情况下启动)。
err := cmd.Run()
if err != nil {
log.Fatal(err)
}
fmt.Printf("in all caps: %q\n", out.String())
英文:
"os/exec" is the Go package used to run external programs, which would include Linux utilities.
// The command name is the first arg, subsequent args are the
// command arguments.
cmd := exec.Command("tr", "a-z", "A-Z")
// Provide an io.Reader to use as standard input (optional)
cmd.Stdin = strings.NewReader("some input")
// And a writer for standard output (also optional)
var out bytes.Buffer
cmd.Stdout = &out
// Run the command and wait for it to finish (the are other
// methods that allow you to launch without waiting.
err := cmd.Run()
if err != nil {
log.Fatal(err)
}
fmt.Printf("in all caps: %q\n", out.String())
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论