dsdfd2322 2016-07-18 23:04
浏览 112

在golang中运行系统命令就像在perl中运行系统命令

I am trying to run the system commands in golang. I want the stdout to be printint directly out onto the screen. In golang I use the following now :

out, err := exec.Command(cmd).Output()
    if err != nil {
        fmt.Println("error occured")
        fmt.Printf("%s", err)
   }

Here I am storing the output into "out" variable and then printing that onto the screen. But I want something which prints as a normal shell command like the system() command in perl.

in perl:

system("ls -l");

We don't need to store anything here.

is there some command in golang which mimics exactly the system() cmd in perl.

  • 写回答

2条回答 默认 最新

  • duan1443 2016-07-19 01:00
    关注

    I can't see any built in options for what you want - but a 7 line function would suffice, I believe:

    func system(cmd string, arg ...string) {
        out, err := exec.Command(cmd, arg...).Output()
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(string(out))
    }
    

    Then you can simply call it:

    system("ls", "-l")
    

    So a working full example would be:

    package main
    
    import (
        "fmt"
        "log"
        "os/exec"
    )
    
    func main() {
        system("ls", "-l")
    }
    
    func system(cmd string, arg ...string) {
        out, err := exec.Command(cmd, arg...).Output()
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(string(out))
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 在matlab中Application Compiler后的软件无法打开
  • ¥15 想问一下STM32创建工程模板时遇到得问题
  • ¥15 Fiddler抓包443
  • ¥20 Qt Quick Android 项目报错及显示问题
  • ¥15 而且都没有 OpenCVConfig.cmake文件我是不是需要安装opencv,如何解决?
  • ¥15 oracleBIEE analytics
  • ¥15 H.264选择性加密例程
  • ¥50 windows的SFTP服务器如何能批量同步用户信息?
  • ¥15 centos7.9升级python3.0的问题
  • ¥15 安装CentOS6时卡住