[Python] input()과 sys.stdin

2021. 2. 9. 17:02Programming Language/Python

sys.stdin

알고리즘 문제를 풀 때, 파이썬의 input()은 실행시간이 느려서 자주 시간초과가 난다. 이럴때 sys모듈의 stdin을 사용하면 더 빠르게 input이 가능하다.. 고 하는데, 나는  input()sys.stdin의 차이점을 알고싶었다.

 

input() vs sys.stdin

input()

input() 파이썬의 내장함수이고, 공식 문서의 'Built in function'에가면 해당 내용을 읽어 볼 수 있다.

 

input()에 대한 파이썬 공식 문서

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

대충

prompt에 argument가 존재하면, 개행 없이 표준 출력에 쓰여진다.
input()은 입력으로부터 한 줄을 읽은 뒤, 그것을 (개행을 지우고) 문자열로 변환한 후 return 한다. EOF(End of file)을 읽으면 EOF에러를 일으킨다.

이런 뜻이다.

 

따라서 input()

input -> 개행문자를 벗겨 내어 -> 문자열로 변환 -> return

 

의 절차를 거친다.

 

sys.stdin

sys의 stdin에 대한 파이썬 공식 문서

File objects used by the interpreter for standard input, output and errors:

  • stdin is used for all interactive input (including calls to input());

    stdin은 모든 상호작용하는 입력에 사용된다.(input()으로 인한 call도 포함한다.)

  • stdout is used for the output of print() and > - expression statements and for the prompts of input();

    stdout은 print()로 인한 출력과 표현식으로 인한 출력, 그리고 input()의 prompt에 대한 출력에 사용된다.

  • The interpreter’s own prompts and its error messages go to stderr.

    인터프리터 그 자신의 prompt와 에러메세지는 표준 에러로 전송된다.

 

내장함수인 input()과 달리 sys.stdin은 file object이다.
사용자의 입력을 받는 buffer를 만들어 그 buffer에서 읽어들이는 것이다.

그래서,

input()raw_input()을 evaluate 한 결과를 반환하고 sys.stdin.readline()은 한 줄의 문자열을 반환한다.

캐릭터 단위로 읽어들이는것이 (input(), Scanner() - Java)이기때문에 한번에 읽어와 버퍼에 보관하고 사용자가 요구할 때 버퍼에서 읽어오게 하는 것 (sys.stdin, BufferedReader())이 더 빠르다.

 

 

사용 예제

sys모듈을 import하여 사용한다.

import sys

 

sys.stdin - 여러줄 입력 받을 때

nums = []
for line in sys.stdin:
    nums.append(line)

print(nums)
"""
1
2
3
4
5
^Z
['1\n', '2\n', '3\n', '4\n', '5\n']
"""

sys.stdin^Z를 입력받으면 종료되며, 위 결과에서 보다시피 개행문자까지 입력되는걸 볼 수 있다.
따라서 strip()이나 rstrip()으로 제거해 주어야 한다.

nums.append(line.strip())
"""
1
2
3
4
5
^Z
['1', '2', '3', '4', '5']
"""

 

sys.stdin.readline() - 한 줄 입력

x, y = sys.stdin.readline().split()

print("x = ", x)
print("y = ", y)
"""
x =  1
y =  2
"""

 

sys.stdin.readline() 사용한 여러줄 입력

for문을 사용하면 된다.
백준에서 입력값의 갯수를 N으로 주는 경우가 많은데, 그런 경우는 리스트 컴프리헨션을 이용하여

N = input()
a = [sys.stdin.readline() for _ in range(N)]

이렇게 간단하게도 사용 가능하다.

 

참고자료

 

 

반응형