웹사이트 검색

Python에서 stdin에서 읽는 방법


Python에서 stdin에서 데이터를 읽는 세 가지 방법이 있습니다.

  1. sys.stdin
  2. input() 내장 함수
  3. fileinput.input() 함수

1. sys.stdin을 사용하여 표준 입력에서 읽기

rstrip() 함수를 사용하여 제거합니다. 다음은 표준 입력에서 사용자 메시지를 읽고 처리하는 간단한 프로그램입니다. 사용자가 "종료\ 메시지를 입력하면 프로그램이 종료됩니다.

import sys

for line in sys.stdin:
    if 'Exit' == line.rstrip():
        break
    print(f'Processing Message from sys.stdin *****{line}*****')
print("Done")

산출:

Hi
Processing Message from sys.stdin *****Hi
*****
Hello
Processing Message from sys.stdin *****Hello
*****
Exit
Done

사용자가 "Exit\ 메시지를 입력했는지 여부를 확인할 수 있도록 후행 개행 문자를 제거하기 위해 rstrip()을 사용하는 것에 주목하십시오.

2. input() 함수를 사용하여 stdin 데이터 읽기

Python input() 함수를 사용하여 표준 입력 데이터를 읽을 수도 있습니다. 사용자에게 메시지를 표시할 수도 있습니다. 다음은 사용자가 종료 메시지를 입력하지 않는 한 무한 루프에서 표준 입력 메시지를 읽고 처리하는 간단한 예입니다.

while True:
    data = input("Please enter the message:\n")
    if 'Exit' == data:
        break
    print(f'Processing Message from input() *****{data}*****')

print("Done")

산출:

input() 함수는 사용자 메시지에 개행 문자를 추가하지 않습니다.

3. fileinput 모듈을 이용한 Standard Input 읽기

fileinput.input() 함수를 사용하여 표준 입력에서 읽을 수도 있습니다. fileinput 모듈은 표준 입력 또는 파일 목록을 반복하는 유틸리티 함수를 제공합니다. input() 함수에 인수를 제공하지 않으면 표준 입력에서 인수를 읽습니다. 이 함수는 sys.stdin과 같은 방식으로 작동하며 사용자가 입력한 데이터 끝에 개행 문자를 추가합니다.

import fileinput

for fileinput_line in fileinput.input():
    if 'Exit' == fileinput_line.rstrip():
        break
    print(f'Processing Message from fileinput.input() *****{fileinput_line}*****')

print("Done")

산출: