# start-bot — 매매 봇 백그라운드 시작 `app/main.py`를 독립 백그라운드 프로세스로 실행한다. Claude Code가 종료된 뒤에도 봇은 계속 실행된다. ## 실행 순서 ### 1. 기존 봇 전부 종료 (PID 파일 + 프로세스 스캔 병행) ```python import subprocess, os pid_file = r'C:\Users\whdwo\OneDrive\바탕 화면\stockbot_v3\logs\bot.pid' # 1-a) PID 파일로 종료 if os.path.exists(pid_file): try: pid = int(open(pid_file).read().strip()) subprocess.run(['taskkill', '/PID', str(pid), '/F'], capture_output=True) print(f'PID 파일 종료: {pid}') except Exception as e: print(f'PID 파일 종료 실패: {e}') os.remove(pid_file) # 1-b) Get-CimInstance로 잔존 프로세스 스캔해서 모두 종료 r = subprocess.run( ['powershell', '-Command', 'Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -like "*app/main.py*" -or $_.CommandLine -like "*app\\main.py*" } | Select-Object -ExpandProperty ProcessId'], capture_output=True, text=True ) pids = [p.strip() for p in r.stdout.strip().splitlines() if p.strip().isdigit()] for pid in pids: subprocess.run(['taskkill', '/PID', pid, '/F'], capture_output=True) print(f'잔존 프로세스 종료: {pid}') if not pids: print('실행 중인 봇 없음 — 새로 시작합니다') ``` ### 2. 봇 시작 + PID 저장 ```python import subprocess, sys, os os.chdir(r'C:\Users\whdwo\OneDrive\바탕 화면\stockbot_v3') proc = subprocess.Popen( [sys.executable, 'app/main.py'], creationflags=subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP, stdout=open('logs/bot_stderr.log', 'a', encoding='utf-8'), stderr=subprocess.STDOUT, close_fds=True, ) # PID 파일 저장 (다음 재시작 때 확실히 종료하기 위해) with open('logs/bot.pid', 'w') as f: f.write(str(proc.pid)) print(f'봇 시작 완료 PID={proc.pid}') ``` ### 3. Discord 시작 알림 ```python import asyncio, sys, os sys.path.insert(0, '.') from app.main import load_env; load_env() from app.monitor.notifier import send mode = os.getenv('KIS_MOCK', 'true') dry = os.getenv('DRY_RUN', 'true') label = '[모의투자]' if mode == 'true' else '[실거래]' asyncio.run(send(f'{label} 자동매매 봇 시작 (DRY_RUN={dry})')) print('Discord 알림 전송 완료') ``` ### 4. 완료 "봇 시작 완료" 메시지를 출력하고 종료한다.