如何使用”go”语言中的”os/exec”包将文件从一个目录复制到另一个目录?

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

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())

huangapple
  • 本文由 发表于 2017年9月1日 03:42:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/45988978.html
匿名

发表评论

匿名网友

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

确定