Python3 : Using input() how to Read Multiple Lines

2019-06-01 00:19发布

问题:

im just curious while learning python3 and didn't found any good explanation on the web, neither here to my question.

reading about input() it says "reads from stdin" so i thought i might experiment and try to use it to read from pipe. and so it does! but only ONE LINE (till EOL). So the next question that came up was

how to read multiple lines from pipe (stdin) using input() ?

i found sys.stdin and used sys.stdin.isatty() to determine if stdin is bound to a tty or not, assuming that if not bound to tty the data is coming from pipe. and so i also found and used successfully sys.stdin.readlines() too to read multiple lines.

but just for my curiosity , is there a way to achieve the same by using the plain input() function ?? so far i didn't found something "to test" if stdin contains more lines without blocking my program.

sorry if all this makes no sense to you.

this is my experimenting code so far without input():

import sys

if sys.stdin.isatty(): # is this a keyboard?
    print(  "\n\nSorry! i only take input from pipe. " 
            "not from a keyboard or tty!\n"
            "for example:\n$ echo 'hello world' | python3 stdin.py"
            ""
            ""
            )
else:
    print ( "reading from stdin via pipe : \n ")

    for line in sys.stdin.readlines():
        print(line, end="")
#   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ can these two lines be replaced with 
#   some construction using plain old input() ? 

回答1:

if you just want to use input() to access lines of the stdin:

print(input()) #prints line 1
print(input()) #prints next line

but lets say you only wanted to access the second line:

input() #accesses the first line
print(input()) #prints second line

Lets say you wanted to take the second line and create an array: stdin:

10

64630 11735 14216 99233 14470 4978 73429 38120 51135 67060

input()
values = list(map(int, input().split(' ')))

values will equal [64630, 11735, 14216, 99233, 14470, 4978, 73429, 38120, 51135, 67060]



回答2:

You can iterate over lines in stdin like any other iterable object:

for line in sys.stdin:
    # do something

If you want to read the entire thing into one string, use:

s = sys.stdin.read()

Note that iterating over s would then return one character at a time.

Note that it won't read until there is an EOF terminating stdin.