2014-03-07 8 views
4

Go에서 쉘 스크립트를 실행하고 싶습니다. 셸 스크립트는 표준 입력을 취해 결과를 에코합니다.GO lang : 쉘 프로세스와 통신합니다.

GO에서 입력을 입력하고 결과를 사용하고 싶습니다.

내가 뭐하는 거지입니다 :

cmd := exec.Command("python","add.py") 
    in, _ := cmd.StdinPipe() 

그러나이 어떻게 in에서 읽습니까?

+0

에서 읽을 수는 없지만 작성자입니다. 글쓰기를 해봤습니까? – JimB

답변

7

여기 프로세스에 쓰기 일부 코드이며, 읽는 :

package main 

import (
    "bufio" 
    "fmt" 
    "os/exec" 
) 

func main() { 
    // What we want to calculate 
    calcs := make([]string, 2) 
    calcs[0] = "3*3" 
    calcs[1] = "6+6" 

    // To store the results 
    results := make([]string, 2) 

    cmd := exec.Command("/usr/bin/bc") 

    in, err := cmd.StdinPipe() 
    if err != nil { 
     panic(err) 
    } 

    defer in.Close() 

    out, err := cmd.StdoutPipe() 
    if err != nil { 
     panic(err) 
    } 

    defer out.Close() 

    // We want to read line by line 
    bufOut := bufio.NewReader(out) 

    // Start the process 
    if err = cmd.Start(); err != nil { 
     panic(err) 
    } 

    // Write the operations to the process 
    for _, calc := range calcs { 
     _, err := in.Write([]byte(calc + "\n")) 
     if err != nil { 
      panic(err) 
     } 
    } 

    // Read the results from the process 
    for i := 0; i < len(results); i++ { 
     result, _, err := bufOut.ReadLine() 
     if err != nil { 
      panic(err) 
     } 
     results[i] = string(result) 
    } 

    // See what was calculated 
    for _, result := range results { 
     fmt.Println(result) 
    } 
} 

당신은 다른 goroutines의 프로세스에 /에서 읽기/쓰기 할 수 있습니다.

+0

왜 downvote? 설명없이? – topskip

관련 문제