Skip to content

Instantly share code, notes, and snippets.

@fyears
Created November 28, 2012 14:46
Show Gist options
  • Save fyears/4161739 to your computer and use it in GitHub Desktop.
Save fyears/4161739 to your computer and use it in GitHub Desktop.
python stdin example
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
usage:
cat about.txt | python soinput.py
'''
import sys
def read_in():
lines = sys.stdin.readlines()
for i in range(len(lines)):
lines[i] = lines[i].replace('\n','')
#print lines
return lines
def main():
lines = read_in()
print lines
if __name__ == '__main__':
main()
@dguitarbite
Copy link

to use this I would run it like this
$ echo "Your Text or Cat the file whatever" | python solnput.py
<<o/p>>

@analogpixel
Copy link

def read_in():
   return [x.strip() for x in sys.stdin.readlines() ]

@Frikster
Copy link

Frikster commented Nov 1, 2017

Concrete example where data flows into script using stdin from some previous program (another script). Line by line explanations for code below can be found here

# stdin.py
sys.stdout = fsock
print("15\n"
"A\n"
"B\n"
"C\n"
"D\n"
"E\n"
"F\n"
"G\n"
"H")
sys.stdout = saveout
fsock.close()
# stdin.py
def read_in():
    return {x.strip() for x in sys.stdin}

def main():
    lines = read_in()
    for line in lines:
        print(line)

if __name__ == '__main__':
    main()

In the console, run this to see above working. Why this works is also explained here

>>>Python3.5 stdout.py
>>>cat out.log | Python3.5 stdin.py

@ViktorHaag
Copy link

ViktorHaag commented Feb 22, 2018

If you use a set ( { ... } ) for the reading of lines, you won't necessarily get them back in the same order, though, right?

return {x.strip() for x in sys.stdin}

You probably want to be using a list comprehension instead, so the read input will stay in the order of having been read:

return [x.strip() for x in sys.stdin]

@rrrnld
Copy link

rrrnld commented Oct 20, 2018

Thanks for the gist! I've used it to set up an alias to urlencode strings like so, maybe this is helpful to someone:

python3 -c 'import sys; from urllib.parse import quote; print(quote(sys.stdin.readlines()[0]))'

@rioj7
Copy link

rioj7 commented Aug 23, 2019

Most likely you don't want to remove all whitespace from the line, only the trailing newline

def read_in():
   return [x.rstrip('\n') for x in sys.stdin ]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment