AI PROMPTS · 루프 생성 전략
코드 실행 검증 루프
Python 항목은 실제 실행, Kotlin/Java는 컴파일, Go는 go vet으로 검증합니다.
루프 생성 전략
핵심 설명
Python 항목은 실제 실행, Kotlin/Java는 컴파일, Go는 go vet으로 검증합니다.
Python 3.11+ / Docker
#!/usr/bin/env python3
"""
코드 실행 검증기
생성된 코드를 Docker 샌드박스에서 실제 실행해 검증
"""
import subprocess
import tempfile
import os
import re
import json
def strip_html_tags(html: str) -> str:
"""HTML span 태그 제거해 순수 코드 추출"""
return re.sub(r'<[^>]+>', '', html)
def validate_python(code: str) -> tuple[bool, str]:
"""Python 코드 실행 검증"""
clean_code = strip_html_tags(code)
with tempfile.NamedTemporaryFile(suffix='.py', mode='w', delete=False) as f:
f.write(clean_code)
tmp_path = f.name
try:
result = subprocess.run(
['python3', '-c', f'import ast; ast.parse(open("{tmp_path}").read())'],
capture_output=True, text=True, timeout=5
)
if result.returncode != 0:
return False, result.stderr
# 실제 실행 (Docker 샌드박스 권장)
result = subprocess.run(
['python3', tmp_path],
capture_output=True, text=True, timeout=10
)
return result.returncode == 0, result.stderr or result.stdout
except subprocess.TimeoutExpired:
return False, "실행 시간 초과"
finally:
os.unlink(tmp_path)
def validate_go(code: str) -> tuple[bool, str]:
"""Go 코드 문법 검증"""
clean_code = strip_html_tags(code)
with tempfile.TemporaryDirectory() as tmpdir:
# go.mod 생성
with open(os.path.join(tmpdir, 'go.mod'), 'w') as f:
f.write('module temp\ngo 1.22\n')
with open(os.path.join(tmpdir, 'main.go'), 'w') as f:
f.write(clean_code)
result = subprocess.run(
['go', 'vet', './...'],
capture_output=True, text=True,
timeout=15, cwd=tmpdir
)
return result.returncode == 0, result.stderr
def validate_item(item: dict) -> dict:
"""항목의 코드를 검증하고 결과 반환"""
lang = item.get('lang', '')
code = item.get('code', '')
validators = {
'python': validate_python,
'go': validate_go,
}
if lang not in validators:
return {'valid': True, 'note': f'{lang} 검증 미지원'}
valid, output = validators[lang](code)
return {
'valid': valid,
'output': output[:200] if output else '',
'id': item.get('id'),
}
if __name__ == '__main__':
import sys
lang = sys.argv[1] if len(sys.argv) > 1 else 'python'
ctx = {}
exec(open(f'data/{lang}.js').read()
.replace('window.DATA', 'DATA')
.replace('(function () {', '')
.replace('})();', ''), ctx)
items = ctx.get('DATA', {}).get(lang, {}).get('items', [])
passed = 0
failed = []
for item in items[:5]: # 처음 5개만 테스트
result = validate_item(item)
status = '✅' if result['valid'] else '❌'
print(f"{status} {item['id']}: {item['title']}")
if result['valid']:
passed += 1
else:
failed.append(item['id'])
print(f" 오류: {result['output'][:100]}")
print(f"\n통과: {passed}/{len(items[:5])}")Continue Learning
AI Prompts 학습을 이어가세요
총 20개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.