How to read user input until EOF in python?

前端 未结 5 1437
囚心锁ツ
囚心锁ツ 2020-12-14 12:19

I came across this problem in UVa OJ. 272-Text Quotes

Well, the problem is quite trivial. But the thing is I am not able to read the input. The input is provided in

相关标签:
5条回答
  • 2020-12-14 12:49

    You can read input from console till the end of file using sys and os module in python. I have used these methods in online judges like SPOJ several times.

    First method (recommened):

    from sys import stdin
    
    for line in stdin:
        if line == '': # If empty string is read then stop the loop
            break
        process(line) # perform some operation(s) on given string
    

    Note that there will be an end-line character \n at the end of every line you read. If you want to avoid printing 2 end-line characters while printing line use print(line, end='').

    Second method:

    import os
    # here 0 and 10**6 represents starting point and end point in bytes.
    lines = os.read(0, 10**6).strip().splitlines() 
    for x in lines:
        line = x.decode('utf-8') # convert bytes-like object to string
        print(line)
    

    This method does not work on all online judges but it is the fastest way to read input from a file or console.

    Third method:

    while True:
        line = input()
        if line == '':
            break
        process(line)
    

    replace input() with raw_input() if you're still using python 2.

    0 讨论(0)
  • 2020-12-14 12:50

    This how you can do it :

    while True:
       try :
          line = input()
          ...
       except EOFError:
          pass
    
    0 讨论(0)
  • 2020-12-14 12:54

    If you need to read one character on the keyboard at a time, you can see an implementation of getch in Python: Python read a single character from the user

    0 讨论(0)
  • 2020-12-14 13:02

    You can use sys module:

    import sys
    
    complete_input = sys.stdin.read()
    

    sys.stdin is a file like object that you can treat like a Python File object.

    From the documentation:

    Help on built-in function read:

    read(size=-1, /) method of _io.TextIOWrapper instance Read at most n characters from stream.

    Read from underlying buffer until we have n characters or we hit EOF.
    If n is negative or omitted, read until EOF.
    
    0 讨论(0)
  • 2020-12-14 13:07

    For HackerRank and HackerEarth platform below implementation is preferred:

    while True:
    try :
        line = input()
        ...
    except EOFError:
        break;
    
    0 讨论(0)
提交回复
热议问题