Ruan Bekker's Blog

From a Curious mind to Posts on Github

Using the Python Sys Library to Read Data From Stdin

Using Python’s sys library to read data from stdin.

In this basic example we will strip our input, delimited by the comma character, add it to a list, and print it out

Python: Read Data from Standard Input

1
2
3
4
5
6
7
8
9
10
11
12
13
import sys
import json

mylist = []

data_input = sys.stdin.read()
destroy_newline = data_input.replace('\n', '')
mylist = destroy_newline.split(', ')

print("Stripping each word and adding it to 'mylist'")
print("Found: {} words in 'mylist'".format(len(mylist)))
for x in mylist:
    print("Word: {}".format(x))

We will echo three words and pipe it into our python script:

1
2
3
4
5
6
$ echo "one, two, three" | python basic-stdin.py
Stripping each word and adding it to 'mylist'
Found: 3 words in 'mylist'
Word: one
Word: two
Word: three