잠들기 전 PC 자동 종료, 이제 걱정 끝! 🌙💤

잠들기 전 PC 자동 종료, 이제 걱정 끝! 🌙💤 | 지식에 대한 탐구

“밤새 켜져 있는 PC 때문에 전기 요금 폭탄 맞으셨나요? 영화 보다 잠들어 PC를 끄지 못한 적 있으신가요? 이제 그런 걱정은 붙들어 매세요! 우리의 PC 종료 타이머가 여러분의 밤을 지켜드립니다.”

안녕하세요, 테크 애호가 여러분! 오늘은 정말 유용한 프로그램을 소개해드리려고 합니다. 바로 ‘PC 종료 타이머’인데요. 이 프로그램을 사용하면 원하는 시간에 자동으로 PC를 종료할 수 있습니다. 영화 감상이나 대용량 다운로드 후 PC를 끄는 것을 잊어버리는 일이 다시는 없을 거예요!

이 가이드를 따라가다 보면, 여러분도 금방 이 유용한 프로그램을 설치하고 사용할 수 있을 겁니다. 자, 그럼 시작해볼까요?

 

목차

  1. 준비물
  2. Python 설치하기
  3. PC 종료 타이머 스크립트 만들기
  4. 실행 파일(BAT) 만들기
  5. 프로그램 실행하기
  6. 사용 팁
  7. 문제 해결
  8. 마치며

 

준비물

시작하기 전에, 다음 항목들이 필요합니다:

  • 윈도우 PC (이 가이드는 Windows 10을 기준으로 작성되었습니다)
  • 인터넷 연결
  • 약간의 모험심과 호기심 😉

 

Python 설치하기

우리의 PC 종료 타이머는 Python이라는 프로그래밍 언어로 작성되었습니다. 따라서 먼저 Python을 설치해야 해요.

  1. Python 공식 웹사이트에 접속합니다.
  2. 큰 노란색 버튼 “Download Python X.X.X”을 클릭합니다. (X.X.X는 최신 버전 번호입니다)
  3. 다운로드된 설치 파일을 실행합니다.
  4. 설치 창이 뜨면 “Add Python X.X to PATH”라는 체크박스를 꼭 체크해주세요!
  5. “Install Now”를 클릭하고 설치를 진행합니다.
  6. 설치가 완료되면 “Close” 버튼을 클릭합니다.

축하합니다! 이제 Python이 설치되었어요. 다음 단계로 넘어가볼까요?

 

PC 종료 타이머 스크립트 만들기

이제 실제로 PC를 종료할 타이머 프로그램을 만들어볼 거예요. 걱정 마세요, 이미 준비된 코드를 그대로 복사하기만 하면 됩니다!

  1. 메모장을 실행합니다. (시작 메뉴에서 “메모장” 또는 “Notepad”를 검색하세요)
  2. 아래의 코드를 메모장에 복사해 붙여넣습니다:
# PC 종료 타이머 GUI 프로그램
import tkinter as tk
from tkinter import messagebox
import os
import threading

class ShutdownTimer:
    def __init__(self, master):
        self.master = master
        master.title("PC 종료 타이머")
        master.geometry("300x200")
        master.resizable(False, False)

        # 시간 입력 프레임
        time_frame = tk.Frame(master)
        time_frame.pack(pady=20)

        tk.Label(time_frame, text="시간:").grid(row=0, column=0)
        self.hour_entry = tk.Entry(time_frame, width=5)
        self.hour_entry.grid(row=0, column=1)
        tk.Label(time_frame, text="분:").grid(row=0, column=2)
        self.minute_entry = tk.Entry(time_frame, width=5)
        self.minute_entry.grid(row=0, column=3)

        # 버튼 프레임
        button_frame = tk.Frame(master)
        button_frame.pack(pady=10)

        self.start_button = tk.Button(button_frame, text="타이머 시작", command=self.start_timer)
        self.start_button.pack(side=tk.LEFT, padx=10)

        self.cancel_button = tk.Button(button_frame, text="취소", command=self.cancel_timer, state=tk.DISABLED)
        self.cancel_button.pack(side=tk.LEFT, padx=10)

        # 상태 라벨
        self.status_label = tk.Label(master, text="")
        self.status_label.pack(pady=10)

        self.timer_thread = None
        self.is_running = False

    def start_timer(self):
        try:
            hours = int(self.hour_entry.get() or 0)
            minutes = int(self.minute_entry.get() or 0)

            if hours == 0 and minutes == 0:
                messagebox.showerror("오류", "시간을 입력해주세요.")
                return

            total_seconds = (hours * 3600) + (minutes * 60)

            self.is_running = True
            self.start_button.config(state=tk.DISABLED)
            self.cancel_button.config(state=tk.NORMAL)
            self.status_label.config(text=f"{hours}시간 {minutes}분 후에 PC가 종료됩니다.")

            self.timer_thread = threading.Thread(target=self.run_timer, args=(total_seconds,))
            self.timer_thread.start()

        except ValueError:
            messagebox.showerror("오류", "올바른 숫자를 입력해주세요.")

    def run_timer(self, seconds):
        while seconds > 0 and self.is_running:
            minutes, secs = divmod(seconds, 60)
            hours, minutes = divmod(minutes, 60)
            self.status_label.config(text=f"남은 시간: {hours:02d}:{minutes:02d}:{secs:02d}")
            self.master.update()
            threading.Event().wait(1)
            seconds -= 1

        if self.is_running:
            self.status_label.config(text="PC를 종료합니다...")
            os.system("shutdown /s /t 1")

    def cancel_timer(self):
        self.is_running = False
        if self.timer_thread:
            self.timer_thread.join()
        self.start_button.config(state=tk.NORMAL)
        self.cancel_button.config(state=tk.DISABLED)
        self.status_label.config(text="타이머가 취소되었습니다.")

if __name__ == "__main__":
    root = tk.Tk()
    app = ShutdownTimer(root)
    root.mainloop()
  1. 파일 > 다른 이름으로 저장을 클릭합니다.
  2. 저장 위치를 ‘D:\’ (D 드라이브의 루트 폴더)로 지정합니다.
  3. 파일 이름을 ‘pc_shutdown_timer_gui.py’로 입력합니다.
  4. 파일 형식을 ‘모든 파일 (*.*)’로 변경합니다.
  5. 인코딩이 ‘UTF-8’로 설정되어 있는지 확인합니다.
  6. ‘저장’ 버튼을 클릭합니다.

훌륭해요! 이제 PC 종료 타이머의 핵심 코드가 준비되었습니다. 다음은 이 프로그램을 쉽게 실행할 수 있는 실행 파일을 만들어볼 거예요.

 

실행 파일(BAT) 만들기

Python 스크립트를 직접 실행할 수도 있지만, 더 편리하게 사용하기 위해 BAT 파일을 만들어볼 거예요.

  1. 메모장을 새로 엽니다.
  2. 아래의 코드를 복사해 붙여넣습니다:
@echo off
chcp 949
title PC Shutdown Timer Launcher
echo Launching PC Shutdown Timer...
echo.

REM Set Python script path
set SCRIPT_PATH=D:\pc_shutdown_timer_gui.py

REM Check if the script file exists
if not exist %SCRIPT_PATH% (
    echo Error: Cannot find %SCRIPT_PATH%
    echo Please make sure the Python script file is in the D: drive root.
    pause
    exit /b
)

REM Check if Python is installed and in system path
where python >nul 2>nul
if %ERRORLEVEL% neq 0 (
    echo Python is not installed or not in the system path.
    echo Please install Python and add it to the system path, then try again.
    pause
    exit /b
)

REM Run Python script with admin privileges
echo Running Python script with admin privileges...
powershell -Command "Start-Process python -ArgumentList '%SCRIPT_PATH%' -Verb RunAs"

if %ERRORLEVEL% neq 0 (
    echo Error: Failed to run the Python script.
    echo Please check if you have necessary permissions and try again.
    pause
    exit /b
)

echo.
echo The program is running in a new window. You can close this window.
pause
  1. 파일 > 다른 이름으로 저장을 클릭합니다.
  2. 원하는 위치(예: 바탕화면)를 선택합니다.
  3. 파일 이름을 ‘run_shutdown_timer.bat’로 입력합니다.
  4. 파일 형식을 ‘모든 파일 (*.*)’로 변경합니다.
  5. 인코딩을 ‘ANSI’로 변경합니다. (이 부분이 중요해요!)
  6. ‘저장’ 버튼을 클릭합니다.

잘 하셨어요! 이제 PC 종료 타이머를 실행할 준비가 모두 끝났습니다.

 

프로그램 실행하기

자, 이제 우리가 만든 프로그램을 실행해볼 차례입니다!

  1. ‘run_shutdown_timer.bat’ 파일을 더블클릭합니다.
  2. 사용자 계정 컨트롤(UAC) 창이 뜨면 ‘예’를 클릭합니다.
  3. 잠시 기다리면 PC 종료 타이머 창이 나타납니다.
  4. ‘시간’과 ‘분’ 칸에 원하는 시간을 입력합니다. (예: 2시간 30분 후에 종료하려면 시간에 2, 분에 30을 입력)
  5. ‘타이머 시작’ 버튼을 클릭합니다.
  6. 타이머가 시작되고, 남은 시간이 표시됩니다.

이제 설정한 시간이 지나면 PC가 자동으로 종료될 거예요. 편안히 휴식을 취하세요!

 

사용 팁

  1. 취소하기: 타이머를 중간에 취소하고 싶다면 ‘취소’ 버튼을 클릭하세요.
  2. 바로가기 만들기: ‘run_shutdown_timer.bat’ 파일의 바로가기를 만들어 바탕화면에 놓으면 더 빠르게 실행할 수 있어요.
  3. 관리자 권한: 이 프로그램은 PC를 종료해야 하므로 관리자 권한이 필요합니다. UAC 창이 뜨는 것은 정상이에요.
  4. 정기적인 사용: 매일 밤 같은 시간에 PC를 종료하고 싶다면, 작업 스케줄러를 사용해 이 프로그램을 자동으로 실행할 수 있습니다.

 

문제 해결

  1. “Python이 설치되어 있지 않습니다” 오류
    • Python을 제대로 설치했는지 확인하세요.
    • 설치 시 “Add Python X.X to PATH” 옵션을 체크했는지 확인하세요.
    • PC를 재부팅해보세요.
  2. “스크립트 파일을 찾을 수 없습니다” 오류
    • ‘pc_shutdown_timer_gui.py’ 파일이 D 드라이브의 루트 폴더에 있는지 확인하세요.
    • 파일 이름이 정확한지 다시 한 번 확인하세요.
  3. 프로그램이 실행되지 않는 경우
    • 모든 파일을 다시 한 번 저장해보세요. 특히 BAT 파일의 인코딩이 ‘ANSI’로 되어 있는지 확인하세요.
    • 관리자 권한으로 명령 프롬프트를 열고, 직접 Python 스크립트를 실행해보세요. (예: python D:\pc_shutdown_timer_gui.py)
    • 안티바이러스 프로그램이 실행을 차단하고 있는지 확인하세요.
  4. 타이머가 정확하지 않은 경우
    • PC의 시스템 시계가 정확한지 확인하세요.
    • 절전 모드 설정을 확인하고, 필요하다면 타이머 실행 중에는 절전 모드로 전환되지 않도록 설정하세요.
  5. “Permission denied” 오류가 발생하는 경우
    • BAT 파일을 관리자 권한으로 실행해보세요. (파일을 우클릭하고 “관리자 권한으로 실행” 선택)
    • Windows의 보안 설정을 확인하고, 필요하다면 일시적으로 해제해보세요.

 







 

 

마치며

여러분, 정말 수고 많으셨습니다! 이제 여러분만의 PC 종료 타이머가 완성되었어요. 이 프로그램으로 불필요한 전기 소모를 줄이고, PC 사용 시간도 적절히 관리할 수 있게 되었죠.

이 과정을 통해 파이썬 프로그래밍의 기초, 배치 파일 작성, 그리고 간단한 GUI 애플리케이션 실행 방법까지 배우셨을 거예요. 이것은 여러분의 기술적 모험의 시작일 뿐입니다!

 

다음 단계로 나아가기

  1. 코드 이해하기: 파이썬 스크립트의 각 부분이 어떤 역할을 하는지 살펴보세요. 온라인 파이썬 튜토리얼을 통해 더 자세히 배워볼 수 있어요.
  2. 기능 추가하기: 종료 대신 절전 모드로 전환하는 옵션을 추가하거나, 주기적으로 알림을 표시하는 기능을 넣어보는 건 어떨까요?
  3. GUI 개선하기: tkinter에 대해 더 배워서 인터페이스를 더 멋지고 사용자 친화적으로 만들어보세요.
  4. 다른 프로젝트 도전하기: 이번 경험을 바탕으로 다른 유용한 도구들을 만들어보세요. 아이디어의 제한은 없답니다!

프로그래밍의 세계는 무궁무진합니다. 이번 프로젝트가 여러분의 창의성과 문제 해결 능력을 자극하는 즐거운 경험이 되었기를 바랍니다.

앞으로도 계속해서 호기심을 가지고 새로운 것을 배우고 만들어보세요. 그 과정에서 마주치는 모든 도전과 성취가 여러분을 더욱 성장시킬 거예요.

행운을 빕니다, 그리고 즐거운 코딩하세요! 🚀💻✨

© 2024 지식에 대한 탐구. All rights reserved.

전체 코드

pc_shutdown_timer_gui.py

# PC 종료 타이머 GUI 프로그램
import tkinter as tk
from tkinter import messagebox
import os
import threading

class ShutdownTimer:
    def __init__(self, master):
        self.master = master
        master.title("PC 종료 타이머")
        master.geometry("300x200")
        master.resizable(False, False)

        # 시간 입력 프레임
        time_frame = tk.Frame(master)
        time_frame.pack(pady=20)

        tk.Label(time_frame, text="시간:").grid(row=0, column=0)
        self.hour_entry = tk.Entry(time_frame, width=5)
        self.hour_entry.grid(row=0, column=1)
        tk.Label(time_frame, text="분:").grid(row=0, column=2)
        self.minute_entry = tk.Entry(time_frame, width=5)
        self.minute_entry.grid(row=0, column=3)

        # 버튼 프레임
        button_frame = tk.Frame(master)
        button_frame.pack(pady=10)

        self.start_button = tk.Button(button_frame, text="타이머 시작", command=self.start_timer)
        self.start_button.pack(side=tk.LEFT, padx=10)

        self.cancel_button = tk.Button(button_frame, text="취소", command=self.cancel_timer, state=tk.DISABLED)
        self.cancel_button.pack(side=tk.LEFT, padx=10)

        # 상태 라벨
        self.status_label = tk.Label(master, text="")
        self.status_label.pack(pady=10)

        self.timer_thread = None
        self.is_running = False

    def start_timer(self):
        try:
            hours = int(self.hour_entry.get() or 0)
            minutes = int(self.minute_entry.get() or 0)

            if hours == 0 and minutes == 0:
                messagebox.showerror("오류", "시간을 입력해주세요.")
                return

            total_seconds = (hours * 3600) + (minutes * 60)

            self.is_running = True
            self.start_button.config(state=tk.DISABLED)
            self.cancel_button.config(state=tk.NORMAL)
            self.status_label.config(text=f"{hours}시간 {minutes}분 후에 PC가 종료됩니다.")

            self.timer_thread = threading.Thread(target=self.run_timer, args=(total_seconds,))
            self.timer_thread.start()

        except ValueError:
            messagebox.showerror("오류", "올바른 숫자를 입력해주세요.")

    def run_timer(self, seconds):
        while seconds > 0 and self.is_running:
            minutes, secs = divmod(seconds, 60)
            hours, minutes = divmod(minutes, 60)
            self.status_label.config(text=f"남은 시간: {hours:02d}:{minutes:02d}:{secs:02d}")
            self.master.update()
            threading.Event().wait(1)
            seconds -= 1

        if self.is_running:
            self.status_label.config(text="PC를 종료합니다...")
            os.system("shutdown /s /t 1")

    def cancel_timer(self):
        self.is_running = False
        if self.timer_thread:
            self.timer_thread.join()
        self.start_button.config(state=tk.NORMAL)
        self.cancel_button.config(state=tk.DISABLED)
        self.status_label.config(text="타이머가 취소되었습니다.")

if __name__ == "__main__":
    root = tk.Tk()
    app = ShutdownTimer(root)
    root.mainloop()

run_shutdown_timer.bat

@echo off
chcp 949
title PC Shutdown Timer Launcher
echo Launching PC Shutdown Timer...
echo.

REM Set Python script path
set SCRIPT_PATH=D:\pc_shutdown_timer_gui.py

REM Check if the script file exists
if not exist %SCRIPT_PATH% (
    echo Error: Cannot find %SCRIPT_PATH%
    echo Please make sure the Python script file is in the D: drive root.
    pause
    exit /b
)

REM Check if Python is installed and in system path
where python >nul 2>nul
if %ERRORLEVEL% neq 0 (
    echo Python is not installed or not in the system path.
    echo Please install Python and add it to the system path, then try again.
    pause
    exit /b
)

REM Run Python script with admin privileges
echo Running Python script with admin privileges...
powershell -Command "Start-Process python -ArgumentList '%SCRIPT_PATH%' -Verb RunAs"

if %ERRORLEVEL% neq 0 (
    echo Error: Failed to run the Python script.
    echo Please check if you have necessary permissions and try again.
    pause
    exit /b
)

echo.
echo The program is running in a new window. You can close this window.
pause