4

In Python, how can I get data from standard input? I want to be able to specify a text file as an input to the script from the command line.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Bob
  • 10,741
  • 27
  • 89
  • 143

1 Answers1

5

You can use sys.stdin. It acts like a file object, so treat it as one when you use it:

#!/usr/bin/env python
import sys

print sys.stdin.read()

Running this by itself hangs the interpreter, but adding a pipe operator does what it should:

> echo "asd" | python test.py
> asd
Blender
  • 289,723
  • 53
  • 439
  • 496