Go and python call other programs and get program output

  • 2020-04-02 13:24:11
  • OfStack

In c language, system functions can be used to call system commands and get output, and output redirection can also save the output of program execution to a file for use, but it is not very convenient to use. I'll show you how to implement it in python and the go language, where you can save the output of other programs directly as variables for your programs to use.

The following example is named with ls and requires the installation of MinGW and the addition of "C:\MinGW\msys\1.0\bin" into the environment variable.

Call other programs in python and get output

Sample code:


import os
var = os.popen('ls -l').read()
print var

Operation effect (take my machine as an example) :

< img SRC = "border = 0 / / files.jb51.net/file_images/article/201402/20140210112817.jpg? 2014110112940 ">

Use go language to call other programs and get output

The go code:


package main
import (
    "exec" // "os/exec" in go1
    "fmt"
)
func main(){
    cmd := exec.Command("ls", "-l")
    buf, err := cmd.Output()
    fmt.Printf("%sn%s",buf,err)
}

The operation effect is as follows:

< img SRC = "border = 0 / / files.jb51.net/file_images/article/201402/20140210112907.jpg? 2014110113042 ">


Related articles: