kone
ainovel
ainovel

혼자 프로그램 파이썬이나 기타 등등 만들어 쓰시는분들께 드리는 꿀팁

유틸
11,770 views · 18 points
1
1

처음꺼는 텍스트 편집하거나 전처리할때 쓰는거고 (파이썬)

2번째는 게임할때 데이터 저장하고 백업하거나 간단한 조작 하는 오토핫키인데

2번째꺼 만들어서 계속 수정하면서 쓰다가 너무 길어지니 힘들더라고요 ai가 알려주는거 어디 수정해라 해서 토큰 아껴도 해당 구역 일일히 찾기 기능으로 찾고 어디까지 드래그 해서 수정하고 하는게 번거롭고 힘들더라고요

그래서 갑자기 생각나서 이런식으로 해당섹션 별로 구분해서 수정하고 백업되는 식으로 했는데 프로그램 업데이트할때 정말 편하다라고요

2번째 오토핫키 쓰다가 원래 쓰던 텍스트 툴 업데이트하면서 합치다가 생각나서 올립니다

비슷하게 쓰시거나 원래 잘하시던 분은 비슷하게나 더 좋게 당연히 쓰실거 같은데 혹시 모르시는분 있으면 프로그램 ai로 만들거나 업데이트할때 너무 유용해서 알려드려요 탭이 애매해서 유틸로 올려요

==============================================================================

커뮤니티(아카라이브, 디시, 깃허브 등)에 바로 복사해서 올릴 수 있는 기능 설명글 양식과, 다른 사람들이 이 코드를 AI에게 주고 **"내

파이썬 프로그램에도 이 기능 넣어줘"**라고 바로 요청할 수 있는 단독 실행 가능한 표준 템플릿 코드입니다.

1. 커뮤니티 공유용 설명글 (복사해서 바로 사용)

📌 [Python/Tkinter] 스크립트 내장형 "섹션별 코드 관리자 & 리로더" 기능 공유

텍스트 툴이나 GUI 스크립트를 만들다 보면 코드가 1,000줄 ~ 2,000줄이 훌쩍 넘어가서, 특정 기능을 수정할 때마다 마우스 휠을 한참

굴리거나 에디터에서 함수를 일일이 찾아다니기 번거롭습니다.

오토핫키(AHK) 진영에서 자주 쓰이는 "모듈식 섹션 관리자" 아이디어를 파이썬 Tkinter에 그대로 이식한 코드입니다.

💡 핵심 기능:

1. 코드 자동 분할 탐색: 스크립트 내의 주석 구분선(# ===================== / # SEC XX. 이름)을 인식하여

스크립트 전체를 좌측 목록에 섹션별로 자동 분류합니다.

2. 인앱 라이브 에디터: VS Code나 메모장을 따로 열지 않고도 프로그램 내부에서 원하는 섹션만 골라 즉시 수정할 수 있습니다.

3. 안전한 자동 백업: [전체 저장 후 재실행] 클릭 시 Backup 폴더에 날짜/시간별

백업본(Script_YYYYMMDD_HHMMSS.py)을 자동 생성하여 실수로 코드가 날아가는 사고를 방지합니다.

4. 원클릭 재실행 (Hot-Reload): 코드 수정 후 버튼 하나로 프로그램을 저장하고 즉시 다시 켜서(Reload) 수정 사항을 바로

확인할 수 있습니다.

5. 단축키/조작감 최적화: 윈도우 표준 에디터처럼 Ctrl+A 전체 선택 후 → 방향키를 누르면 맨 끝으로 커서가 바로 이동하며, 창

크기/위치 조절 시 config.json에 자동 저장됩니다.

2. AI에게 바로 먹일 수 있는 독립 예시 코드 (단독 실행 가능)

다른 사람들이 복사해서 ChatGPT나 Claude에게 "이 구조를 내 파이썬 GUI 프로그램에도 추가해줘"라고 요청하기 가장 좋은 표준

미니멀 코드입니다. (이 파일 자체를 실행해도 바로 동작합니다.)

# =====================================================================

# SEC 01. 시스템 초기화 및 경로 설정

# =====================================================================

import json

import os

import re

import shutil

import subprocess

import sys

import time

import tkinter as tk

from tkinter import messagebox, scrolledtext, ttk

# 현재 실행 중인 자기 자신의 스크립트 파일 절대 경로

try:

CURRENT_SCRIPT_PATH = os.path.abspath(__file__)

except NameError:

CURRENT_SCRIPT_PATH = os.path.abspath(sys.argv[0])

BASE_DIR = os.path.dirname(CURRENT_SCRIPT_PATH)

CONFIG_FILE = "config.json"

# =====================================================================

# SEC 02. 스크립트 섹션별 관리자 및 코드 에디터 (핵심 모듈)

# =====================================================================

class ScriptSectionManagerWindow(tk.Toplevel):

"""자기 자신의 .py 스크립트를 주석 섹션 단위로 쪼개어 인앱에서 수정/백업/재실행하는 창"""

def init(self, parent):

super().__init__(parent)

self.title("🛠 스크립트 섹션별 관리자")

self.parent = parent

# 부모 창 위에 항상 유지

self.transient(parent)

self.lift()

self.focus_force()

# 창 크기 복원

self.config_data = self._load_config()

self.geometry(self.config_data.get("mgr_geometry", "900x600"))

self.minsize(700, 450)

self.section_names = []

self.section_codes = []

self.current_idx = 0

self._create_widgets()

self.load_all_sections()

self.protocol("WM_DELETE_WINDOW", self.on_close_save)

def loadconfig(self):

p = os.path.join(BASE_DIR, CONFIG_FILE)

if os.path.exists(p):

try:

with open(p, "r", encoding="utf-8") as f:

return json.load(f)

except Exception:

pass

return {}

def on_close_save(self):

p = os.path.join(BASE_DIR, CONFIG_FILE)

data = self._load_config()

data["mgr_geometry"] = self.geometry()

try:

with open(p, "w", encoding="utf-8") as f:

json.dump(data, f, indent=4, ensure_ascii=False)

except Exception:

pass

self.destroy()

def createwidgets(self):

# 상단 바

top_bar = tk.Frame(self, bg="#0044AA", padx=10, pady=8)

top_bar.pack(fill="x")

tk.Label(top_bar, text="🛠 스크립트 섹션별 관리자", font=("맑은 고딕", 11, "bold"), fg="white", bg="#0044AA").pack(side="left")

tk.Label(top_bar, text="※ [재실행] 클릭 시 Backup 폴더에 백업본 생성", font=("맑은 고딕", 9), fg="#D0E0FF", bg="#0044AA").pack(side="right")

# 좌우 분할 팬

paned = ttk.PanedWindow(self, orient="horizontal")

paned.pack(fill="both", expand=True, padx=10, pady=8)

# 좌측: 단일 컬럼 섹션 목록

left_fr = tk.Frame(paned)

paned.add(left_fr, weight=1)

tk.Label(left_fr, text="섹션 목록", font=("맑은 고딕", 9, "bold")).pack(anchor="w", pady=(0, 4))

self.tree = ttk.Treeview(left_fr, columns=("title",), show="headings", selectmode="browse")

self.tree.heading("title", text="섹션명")

self.tree.column("title", stretch=True)

tree_scr = ttk.Scrollbar(left_fr, orient="vertical", command=self.tree.yview)

self.tree.configure(yscrollcommand=tree_scr.set)

self.tree.pack(side="left", fill="both", expand=True)

tree_scr.pack(side="right", fill="y")

self.tree.bind("<<TreeviewSelect>>", self.on_select_section)

# 우측: 에디터

right_fr = tk.Frame(paned)

paned.add(right_fr, weight=3)

self.lbl_sec_name = tk.Label(right_fr, text="섹션 코드", font=("맑은 고딕", 9, "bold"), fg="#0044AA")

self.lbl_sec_name.pack(anchor="w", pady=(0, 4))

self.editor = scrolledtext.ScrolledText(right_fr, wrap="none", font=("Consolas", 10), bg="#FFFFFF", undo=True)

self.editor.pack(fill="both", expand=True)

# 윈도우 표준 커서/선택 조작 바인딩

self.editor.bind("<Control-a>", lambda e: (e.widget.tag_add("sel", "1.0", "end-1c"), e.widget.mark_set("insert", "end-1c"), "break")[2])

self.editor.bind("<Right>", lambda e: (e.widget.mark_set("insert", "sel.last"), e.widget.tag_remove("sel", "1.0", "end"), "break")[2] if e.widget.tag_ranges("sel") else None)

self.editor.bind("<Left>", lambda e: (e.widget.mark_set("insert", "sel.first"), e.widget.tag_remove("sel", "1.0", "end"), "break")[2] if e.widget.tag_ranges("sel") else None)

# 하단 버튼 제어바

btn_bar = tk.Frame(self, padx=10, pady=8, bg="#F0F0F0")

btn_bar.pack(fill="x")

tk.Button(btn_bar, text="💾 현재 섹션 저장", command=self.save_current_section, bg="#E0F2FE", fg="#0369A1", font=("맑은 고딕", 9, "bold"), padx=10).pack(side="left", padx=4)

tk.Button(btn_bar, text="🔄 전체 저장 후 재실행", command=self.save_and_reload, bg="#DCFCE7", fg="#15803D", font=("맑은 고딕", 9, "bold"), padx=10).pack(side="left", padx=4)

tk.Button(btn_bar, text="↩ 되돌리기", command=self.reset_current_section, font=("맑은 고딕", 9), padx=8).pack(side="left", padx=4)

self.lbl_status = tk.Label(btn_bar, text="", font=("맑은 고딕", 9, "bold"), bg="#F0F0F0")

self.lbl_status.pack(side="left", padx=8)

tk.Button(btn_bar, text="닫기", command=self.on_close_save, font=("맑은 고딕", 9), padx=8).pack(side="right")

def load_all_sections(self):

"""'# =================' 와 '# SEC ...' 주석 규칙을 기준으로 섹션 파싱"""

try:

with open(CURRENT_SCRIPT_PATH, "r", encoding="utf-8") as f:

full_code = f.read()

except Exception as e:

messagebox.showerror("오류", f"파일 로드 실패:\n{e}", parent=self)

return

self.section_names = []

self.section_codes = []

for i in self.tree.get_children():

self.tree.delete(i)

pattern = re.compile(r"(#\s*={5,}\s*\n#\s*(SEC\s*\d+.*?|\[.*?\]|[^=\n#]+?)\s*\n#\s*={5,})", re.MULTILINE)

matches = list(pattern.finditer(full_code))

if not matches:

self.section_names.append("전체 스크립트")

self.section_codes.append(full_code)

self.tree.insert("", "end", values=("전체 스크립트",))

else:

if matches[0].start() > 0:

self.section_names.append("스크립트 서두")

self.section_codes.append(full_code[: matches[0].start()])

self.tree.insert("", "end", values=("스크립트 서두",))

for i in range(len(matches)):

start = matches[i].start()

end = matches[i + 1].start() if i + 1 < len(matches) else len(full_code)

title = re.sub(r"\s*\(.*?\)$", "", matches[i].group(2).strip()).strip()

self.section_names.append(matches[i].group(2).strip())

self.section_codes.append(full_code[start:end])

self.tree.insert("", "end", values=(title,))

ch = self.tree.get_children()

if ch:

self.tree.selection_set(ch[0])

self.on_select_section(None)

def on_select_section(self, event):

sel = self.tree.selection()

if not sel:

return

idx = self.tree.index(sel[0])

self.current_idx = idx

self.lbl_sec_name.config(text=f"현재 편집: [{self.section_names[idx]}]")

self.editor.delete("1.0", tk.END)

self.editor.insert("1.0", self.section_codes[idx])

self.lbl_status.config(text="")

def reset_current_section(self):

if 0 <= self.current_idx < len(self.section_codes):

self.editor.delete("1.0", tk.END)

self.editor.insert("1.0", self.section_codes[self.current_idx])

self.lbl_status.config(text="")

def save_current_section(self, make_backup=False):

if not (0 <= self.current_idx < len(self.section_codes)):

return False

self.section_codes[self.current_idx] = self.editor.get("1.0", tk.END).rstrip("\n") + "\n\n"

# 재실행 시에만 Backup 폴더에 1개 생성

if make_backup:

b_dir = os.path.join(BASE_DIR, "Backup")

if not os.path.exists(b_dir):

os.makedirs(b_dir)

t_str = time.strftime("%Y%m%d_%H%M%S")

try:

shutil.copy2(CURRENT_SCRIPT_PATH, os.path.join(b_dir, f"Script_{t_str}.py"))

except Exception:

pass

new_code = "".join(self.section_codes).rstrip("\n") + "\n"

try:

with open(CURRENT_SCRIPT_PATH, "w", encoding="utf-8") as f:

f.write(new_code)

self.lbl_status.config(text="✔ 저장 완료!", fg="#15803D")

self.lift()

return True

except Exception as e:

messagebox.showerror("저장 오류", f"쓰기 실패:\n{e}", parent=self)

return False

def save_and_reload(self):

self.on_close_save()

if self.save_current_section(make_backup=True):

self.parent.destroy()

# 윈도우 및 콘솔 환경 안전 재시작 (작업 폴더 유지)

try:

if sys.platform == "win32":

os.startfile(CURRENT_SCRIPT_PATH)

else:

subprocess.Popen([sys.executable, CURRENT_SCRIPT_PATH], cwd=BASE_DIR)

except Exception:

subprocess.Popen([sys.executable, CURRENT_SCRIPT_PATH], cwd=BASE_DIR)

sys.exit(0)

# =====================================================================

# SEC 03. 내 프로그램 메인 GUI 예시

# =====================================================================

class MainApp:

def init(self, root):

self.root = root

self.root.title("내 메인 프로그램")

self.root.geometry("450x250")

tk.Label(root, text="파이썬 메인 프로그램 화면입니다.", font=("맑은 고딕", 12)).pack(pady=30)

# 상단/헤더에 관리자 호출 버튼 연결

tk.Button(

root,

text="🛠 스크립트 섹션 관리자 열기",

command=lambda: ScriptSectionManagerWindow(self.root),

bg="#0044AA",

fg="white",

font=("맑은 고딕", 10, "bold"),

padx=15,

pady=8

).pack()

# =====================================================================

# SEC 04. 프로그램 실행 진입점

# =====================================================================

if name == "__main__":

root = tk.Tk()

app = MainApp(root)

root.mainloop()

💡 다른 사람들이 AI에게 질문할 때 쓸 프롬프트 예시

"내가 작성 중인 Tkinter 프로그램에 위의 [스크립트 섹션별 관리자] 기능을 붙여주고 싶어.

내 코드의 상단에 버튼을 하나 달아서 클릭하면 이 관리자 창이 열리게 해주고, 내 전체 코드도 # ===================== \n

# SEC XX. 이름 \n # ===================== 형태로 주석을 분류해서 파싱되도록 합쳐줘.

[여기에 본인 코드 붙여넣기]"

18
4 comments
All
Title
Body