dongtuo0828 2017-10-19 11:43
浏览 215
已采纳

如何将exec()与输入参数一起使用?

How can I use exec with multiple argument in go? I've found an example of exec in go, but i don't understand how to use multiple args, this is what i've tried:

cmdName := os.Args[1]

cmdArgs := []string{os.Args[1:]}

cmd := exec.Command(cmdName, cmdArgs...)
  • 写回答

1条回答 默认 最新

  • douwen5681 2017-10-19 12:00
    关注

    Here is an example how to use exec with multiple arguments:

    package main
    
    import (
        "fmt"
        "log"
        "os"
        "os/exec"
    )
    
    func main() {
        args := os.Args[1:]
    
        fmt.Printf("%s
    ", args)
    
        res, err := exec.Command("ls", args...).Output()
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%q
    ", string(res))
    }
    

    Without args:

    echo -e $(go run args.go )
    [] "args.go
    file1
    file2
    file3
    "
    

    With -s and -r args:

    echo -e $(go run args.go -s -r )
    [-s -r] "total 4
    0 file3
    0 file2
    0 file1
    4 args.go
    "
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于PLUS模型中kapaa值的问题
  • ¥15 关于博途V17进行仿真时无法建立连接问题
  • ¥15 请问下这个红框里面是什么文档或者记事本编辑器
  • ¥15 机器学习教材中的例题询问
  • ¥15 求.net core 几款免费的pdf编辑器
  • ¥15 为什么安装HCL 和virtualbox之后没有找到VirtualBoxHost-OnlyNetWork?
  • ¥15 C# P/Invoke的效率问题
  • ¥20 thinkphp适配人大金仓问题
  • ¥20 Oracle替换.dbf文件后无法连接,如何解决?(相关搜索:数据库|死循环)
  • ¥15 数据库数据成问号了,前台查询正常,数据库查询是?号