본문 바로가기

Language/Python

[Python] 파이썬에서 사용하는 input()과 sys.stdin.readline()의 차이점은 무엇인가?

반응형

최근 백준 알고리즘과 프로그래머스를 통해 코딩 테스트(일명 코테) 준비를 위해 알고리즘 문제을 풀이하고 있다.

나는 주로 파이썬이 다른 언어보다 빠르고 간결하게 작성할 수 있고, 파이썬의 강력한 라이브러리들 때문에 파이썬을 사용하여 문제를 풀이하는데 얼마 전 sys.stdin.readline()을 사용하여 문제 풀이를 하는 글을 보고 이 두 개의 차이점이 궁금해졌다.

 

오늘은 파이썬에서 값을 입력할 때 사용하는 input()과 sys.stdin.readline()의 차이점에 대해 글을 쓰고 비교해보려고 한다.

 

사용법


우선 input()의 사용법은 다음과 같다.

아래 코드는 a의 값을 정수형으로 입력받기 위해 int(input())을 사용하여 입력을 받는다.

a = int(input())

print(a)

 

 

 

 

 

 

 

 

 

 

 

 

sys.stdin.readline()의 사용법은 다음과 같다.

input()과는 다르게 'sys' 라이브러리에 포함되어 있기 때문에 'sys'라이브러리를 import 해주어야 한다.

import sys

a = int(sys.stdin.readline())

print(a)

 

 

 

 

 

 

 

 

 

 

출력 결과만 본다면 이 둘의 차이점은 없는 것 처럼 보인다.

차이점


파이썬 공식 문서에 따르면 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.

해석해보면

'prompt인자가 있을 경우 끝에 개행 문자를 붙이지 않고 표준 출력에 쓴다. 그 후 함수는 입력을 통해 한 줄을 읽고, 문자열로 변환하여 (그 이후 줄 바꿈을 제거) 값을 반환한다.'

동작을 그림으로 표현하면 다음과 같다.

그렇다면 sys.stdin.readline()의 경우 어떻게 동작하는 것일까?

 

여기서 sys는 파이썬 인터프리터가 제공하는 변수와 함수를 직접 제어할 수 있게 해주는 모듈이며 파이썬을 할 때 기본적으로 설치가 된다.

 

우선 파이썬 공식문서에 따르면 sys.stdin은 다음과 같이 정의되어 있다.

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

해석을 하자면

'stdin은 모든 대화형 입력에 사용된다. (input() 호출을 포함)'

 

결국은 sys.stdin은 input()과 같은 동작을 한다는 것을 알 수 있다.

 

그렇다면 readline()은 어떤 것을 의미하는지 찾아보았다.

파이썬 공식문서에 따르면 다음과 같이 정의되어 있다.

The readline module defines a number of functions to facilitate completion and reading/writing of history files from the Python interpreter. This module can be used directly, or via the rlcompleter module, which supports completion of Python identifiers at the interactive prompt. Settings made using this module affect the behaviour of both the interpreter’s interactive prompt and the prompts offered by the built-in input() function.

'readline 모듈은 파이썬 인터프리터에서 completion과 history file의 읽기/쓰기를 용이하게 하는 여러 함수를 정의한다.

이 모듈은 직접 사용하거나, 혹은 interactive prompt에서 파이썬 식별자 완성?(completion of python identifiers)을 지원하는 rlcompleter 모듈을 통해서 사용할 수 있다. 이 모듈을 사용하기 위해서 설정하는 것은 interpreter의 대화식 prompts와 내장 input() 함수가 제공하는 prompt 동작에 영향을 준다.'

 

쉽게 정리해보면 sys.stdin은 input()과 같은 동작을 한다. 하지만 input()과 sys.stdin.readline()은 같지 않다고 볼 수 있다.

그 이유는 input()은 내장 함수로써 파라미터로 prompt message을 받아서 사용할 수 있으며, 입력받은 값의 개행 문자를 삭제시켜 반환한다.

하지만 sys.stdin.readline()는 prompt message을 파라미터로 받지 않으며, 개행 문자를 포함하여 반환한다.

 

결론


1. 속도 측면에서는 input() 보다는 sys.stdin.readline()을 사용하는 것이 더 빠르다.

2. 종종 입력 값에서 prompt message가 필요 없는 BOJ에서 시간 초과 문제가 발생할 경우 sys.stdin.readline()을 사용하면 시간 초과 문제를 해결할 수 있다.

 

 

 

참고자료


wikidocs.net/33#sys

 

위키독스

온라인 책을 제작 공유하는 플랫폼 서비스

wikidocs.net

docs.python.org/3/

 

3.9.4 Documentation

Python 3.9.4 documentation Welcome! This is the documentation for Python 3.9.4. Parts of the documentation: What's new in Python 3.9? or all "What's new" documents since 2.0 Tutorial start here Library Reference keep this under your pillow Language Referen

docs.python.org

반응형

'Language > Python' 카테고리의 다른 글

[Python] 채팅 프로그램  (0) 2019.06.03
[Python] 동전 교환 프로그램  (0) 2019.04.19
[Python] 진수 변환 하기  (0) 2019.04.19
2. 파이썬 자료형 - 숫자형  (0) 2018.07.01
1. Window에 파이썬 설치 하기  (0) 2018.07.01


Calendar
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
Visits
Today
Yesterday