본문 바로가기
Python

파이썬 RuntimeError: lost sys.stdin 오류 해결

by 박_은애 2025. 4. 25.
반응형

파이썬 RuntimeError: lost sys.stdin 오류 해결

다음 오류는 PyInstaller로 윈도우용 EXE를 만들면서 표준 입력(stdin)이 사라져 input() 호출 시 RuntimeError: lost sys.stdin 예외가 발생했기 때문입니다. 해결책은 크게 두 가지입니다.


1. 콘솔 모드로 EXE 빌드

PyInstaller 기본값이 GUI(윈도우) 모드(--noconsole)로 되어 있으면 stdin/stdout이 연결되지 않습니다.
콘솔 입출력을 그대로 쓰려면 콘솔 모드로 빌드하세요.

# --console (또는 -c) 옵션을 명시하면 stdin/stdout이 살아 있는 콘솔용 EXE가 생성됩니다.
pyinstaller --onefile --console calculate_daily_tax.py

주의:
GUI 모드(--windowed/--noconsole)로 빌드하면 당연히 input()을 사용할 수 없습니다.


2. stdin 복구 로직 추가

콘솔 모드를 쓸 수 없는 상황이거나, 그래도 예외를 우회하고 싶다면 아래처럼 input()을 래핑해 RuntimeError 발생 시 Windows의 CONIN$(콘솔 입력)로 stdin을 재연결하도록 처리할 수 있습니다.

#!/usr/bin/env python3
# filename: calculate_daily_tax.py

import sys, os

def safe_input(prompt: str) -> str:
    """
    input() 호출 중 'lost sys.stdin' 예외가 발생하면
    Windows 콘솔 입력 핸들(CONIN$)을 다시 연결합니다.
    """
    try:
        return input(prompt)
    except RuntimeError as e:
        if os.name == 'nt' and 'lost sys.stdin' in str(e):
            # Windows 콘솔 입력 핸들 복구
            sys.stdin = open('CONIN$', 'r')
            return input(prompt)
        raise

def calculate_daily_tax(daily_wage, work_days):
    gross = daily_wage * work_days
    deduction = 150_000 * work_days
    taxable_income = max(gross - deduction, 0)
    basic_tax = taxable_income * 0.06
    reduced_tax = basic_tax * (1 - 0.55)
    withholding_tax = reduced_tax * 1.1
    return round(withholding_tax)

def main():
    print("=== 일용직 소득세 계산기 ===")
    try:
        daily_str = safe_input("1. 일급여를 입력하세요(원): ").replace(',', '')
        days_str  = safe_input("2. 근무일수를 입력하세요(일): ")
        daily = int(daily_str)
        days  = int(days_str)
    except ValueError:
        print("▶ 올바른 숫자를 입력해주세요.")
        return

    tax = calculate_daily_tax(daily, days)
    print("\n--- 계산 결과 ---")
    print(f"총 급여액    : {daily * days:,}원")
    print(f"원천징수세액 : {tax:,}원")
    print("※ 세액이 1,000원 미만인 경우 소액부징수될 수 있습니다.")

if __name__ == "__main__":
    main()

이렇게 하면…

  1. 콘솔 모드로 빌드할 수 없는 상황에서도
  2. RuntimeError: lost sys.stdin 예외를 잡아내
  3. Windows 콘솔 입력 핸들을 재연결하여 input()을 이어서 사용할 수 있습니다.

요약

  • 가장 간단한 방법: PyInstaller를 --console 옵션과 함께 빌드
  • 대안: safe_input() 함수처럼 예외 발생 시 CONIN$로 stdin을 재연결

위 두 방법 중 하나를 적용하시면 더 이상 lost sys.stdin 에러 없이 정상적으로 일용직 소득세 계산기를 실행하실 수 있습니다.

반응형