Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read from initial stdin in Go?

Tags:

go

I would like to read from the original stdin of a Go program. For example, if I did echo test stdin | go run test.go, I would want to have access to "test stdin". I've tried reading from os.Stdin, but if there's nothing in it, then it will wait for input. I also tried checking the size first, but the os.Stdin.Stat().Size() is 0 even when input is passed in.

What can I do?

like image 434
mowwwalker Avatar asked Sep 11 '12 05:09

mowwwalker


1 Answers

Reading from stdin using os.Stdin should work as expected:

package main  import "os" import "log" import "io/ioutil"  func main() {     bytes, err := ioutil.ReadAll(os.Stdin)      log.Println(err, string(bytes)) } 

Executing echo test stdin | go run stdin.go should print 'test stdin' just fine.

It would help if you'd attach the code you used to identify the problem you encountered.

For line based reading you can use bufio.Scanner:

import "os" import "log" import "bufio"  func main() {     s := bufio.NewScanner(os.Stdin)     for s.Scan() {         log.Println("line", s.Text())     } } 
like image 184
nemo Avatar answered Sep 28 '22 20:09

nemo