Claude는 Anthropic에서 정의한 텍스트 에디터 도구를 사용하여 텍스트 파일을 보고 수정할 수 있으며, 이를 통해 코드나 기타 텍스트 문서를 디버깅, 수정 및 개선하는 데 도움을 줍니다. 이를 통해 Claude는 단순히 변경 사항을 제안하는 것이 아니라 파일과 직접 상호 작용하여 실질적인 도움을 제공할 수 있습니다.
Messages API를 사용하여 Claude에 텍스트 에디터 도구(이름: str_replace_based_edit_tool)를 제공합니다:
import anthropicclient = anthropic.Anthropic()response = client.messages.create( model="claude-opus-4-20250514", max_tokens=1024, tools=[{"type":"text_editor_20250429","name":"str_replace_based_edit_tool"}], messages=[{"role":"user","content":"There's a syntax error in my primes.py file. Can you help me fix it?"}])
Messages API를 사용하여 Claude에 텍스트 에디터 도구(이름: str_replace_based_edit_tool)를 제공합니다:
import anthropicclient = anthropic.Anthropic()response = client.messages.create( model="claude-opus-4-20250514", max_tokens=1024, tools=[{"type":"text_editor_20250429","name":"str_replace_based_edit_tool"}], messages=[{"role":"user","content":"There's a syntax error in my primes.py file. Can you help me fix it?"}])
Messages API를 사용하여 Claude에 텍스트 에디터 도구(이름: str_replace_editor)를 제공합니다:
import anthropicclient = anthropic.Anthropic()response = client.messages.create( model="claude-3-7-sonnet-20250124", max_tokens=1024, tools=[{"type":"text_editor_20250124","name":"str_replace_editor"}], messages=[{"role":"user","content":"There's a syntax error in my primes.py file. Can you help me fix it?"}])
Messages API를 사용하여 Claude에 텍스트 에디터 도구(이름: str_replace_editor)를 제공합니다:
import anthropicclient = anthropic.Anthropic()response = client.messages.create( model="claude-3-5-sonnet-20241022", max_tokens=1024, tools=[{"type":"text_editor_20241022","name":"str_replace_editor"}], messages=[{"role":"user","content":"There's a syntax error in my primes.py file. Can you help me fix it?"}])
텍스트 에디터 도구는 다음과 같은 방식으로 사용할 수 있습니다:
1
Claude에 텍스트 에디터 도구와 사용자 프롬프트 제공
API 요청에 텍스트 에디터 도구 포함
“내 코드의 구문 오류를 수정해 줄 수 있나요?”와 같이 파일 검사나 수정이 필요한 사용자 프롬프트 제공
2
Claude가 도구를 사용하여 파일이나 디렉토리 검사
Claude는 무엇을 살펴봐야 할지 평가하고 view 명령을 사용하여 파일 내용을 검사하거나 디렉토리 내용을 나열
API 응답에는 view 명령이 포함된 tool_use 콘텐츠 블록이 포함됨
3
view 명령 실행 및 결과 반환
Claude의 도구 사용 요청에서 파일 또는 디렉토리 경로 추출
파일 내용을 읽거나 디렉토리 내용을 나열하고 Claude에 반환
tool_result 콘텐츠 블록이 포함된 새로운 user 메시지로 대화를 계속하여 Claude에 결과 반환
4
Claude가 도구를 사용하여 파일 수정
파일이나 디렉토리를 검사한 후, Claude는 변경을 위해 str_replace 명령이나 특정 줄 번호에 텍스트를 추가하기 위한 insert 명령을 사용할 수 있음
Claude가 str_replace 명령을 사용하는 경우, 이전 텍스트와 이를 대체할 새 텍스트가 포함된 적절한 형식의 도구 사용 요청을 구성
5
편집 실행 및 결과 반환
Claude의 도구 사용 요청에서 파일 경로, 이전 텍스트 및 새 텍스트 추출
파일에서 텍스트 대체 수행
Claude에 결과 반환
6
Claude가 분석 및 설명 제공
파일을 검사하고 가능한 편집한 후, Claude는 발견한 내용과 변경한 내용에 대한 완전한 설명 제공
view 명령을 사용하면 Claude가 파일 내용을 검사하거나 디렉토리 내용을 나열할 수 있습니다. 전체 파일이나 특정 범위의 줄을 읽을 수 있습니다.
매개변수:
command: “view”여야 함
path: 보려는 파일 또는 디렉토리의 경로
view_range (선택 사항): 보려는 시작 및 끝 줄 번호를 지정하는 두 개의 정수 배열. 줄 번호는 1부터 시작하며, 끝 줄에 -1은 파일 끝까지 읽는다는 의미입니다. 이 매개변수는 디렉토리가 아닌 파일을 볼 때만 적용됩니다.
// 파일 보기 예시{"type":"tool_use","id":"toolu_01A09q90qw90lq917835lq9","name":"str_replace_editor","input":{"command":"view","path":"primes.py"}}// 디렉토리 보기 예시{"type":"tool_use","id":"toolu_02B19r91rw91mr917835mr9","name":"str_replace_editor","input":{"command":"view","path":"src/"}}
str_replace 명령을 사용하면 Claude가 파일에서 특정 문자열을 새 문자열로 대체할 수 있습니다. 이는 정확한 편집을 위해 사용됩니다.
매개변수:
command: “str_replace”여야 함
path: 수정할 파일의 경로
old_str: 대체할 텍스트(공백과 들여쓰기를 포함하여 정확히 일치해야 함)
new_str: 이전 텍스트 대신 삽입할 새 텍스트
{"type":"tool_use","id":"toolu_01A09q90qw90lq917835lq9","name":"str_replace_editor","input":{"command":"str_replace","path":"primes.py","old_str":"for num in range(2, limit + 1)","new_str":"for num in range(2, limit + 1):"}}
insert 명령을 사용하면 Claude가 파일의 특정 위치에 텍스트를 삽입할 수 있습니다.
매개변수:
command: “insert”여야 함
path: 수정할 파일의 경로
insert_line: 텍스트를 삽입할 줄 번호(파일 시작 부분은 0)
new_str: 삽입할 텍스트
{"type":"tool_use","id":"toolu_01A09q90qw90lq917835lq9","name":"str_replace_editor","input":{"command":"insert","path":"primes.py","insert_line":0,"new_str":"\"\"\"Module for working with prime numbers.\n\nThis module provides functions to check if a number is prime\nand to generate a list of prime numbers up to a given limit.\n\"\"\"\n"}}
이 예시는 Claude 4가 텍스트 에디터 도구를 사용하여 Python 파일의 구문 오류를 수정하는 방법을 보여줍니다.
먼저, 애플리케이션이 Claude에 텍스트 에디터 도구와 구문 오류를 수정하는 프롬프트를 제공합니다:
import anthropicclient = anthropic.Anthropic()response = client.messages.create( model="claude-opus-4-20250514", max_tokens=1024, tools=[{"type":"text_editor_20250429","name":"str_replace_based_edit_tool"}], messages=[{"role":"user","content":"There's a syntax error in my primes.py file. Can you help me fix it?"}])print(response)
Claude는 먼저 텍스트 에디터 도구를 사용하여 파일을 볼 것입니다:
{"id":"msg_01XAbCDeFgHiJkLmNoPQrStU","model":"claude-opus-4-20250514","stop_reason":"tool_use","role":"assistant","content":[{"type":"text","text":"I'll help you fix the syntax error in your primes.py file. First, let me take a look at the file to identify the issue."},{"type":"tool_use","id":"toolu_01AbCdEfGhIjKlMnOpQrStU","name":"str_replace_based_edit_tool","input":{"command":"view","path":"primes.py"}}]}
그런 다음 애플리케이션은 파일을 읽고 그 내용을 Claude에 반환해야 합니다:
response = client.messages.create( model="claude-opus-4-20250514", max_tokens=1024, tools=[{"type":"text_editor_20250429","name":"str_replace_based_edit_tool"}], messages=[{"role":"user","content":"There's a syntax error in my primes.py file. Can you help me fix it?"},{"role":"assistant","content":[{"type":"text","text":"I'll help you fix the syntax error in your primes.py file. First, let me take a look at the file to identify the issue."},{"type":"tool_use","id":"toolu_01AbCdEfGhIjKlMnOpQrStU","name":"str_replace_based_edit_tool","input":{"command":"view","path":"primes.py"}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_01AbCdEfGhIjKlMnOpQrStU","content":"1: def is_prime(n):\n2: \"\"\"Check if a number is prime.\"\"\"\n3: if n <= 1:\n4: return False\n5: if n <= 3:\n6: return True\n7: if n % 2 == 0 or n % 3 == 0:\n8: return False\n9: i = 5\n10: while i * i <= n:\n11: if n % i == 0 or n % (i + 2) == 0:\n12: return False\n13: i += 6\n14: return True\n15: \n16: def get_primes(limit):\n17: \"\"\"Generate a list of prime numbers up to the given limit.\"\"\"\n18: primes = []\n19: for num in range(2, limit + 1)\n20: if is_prime(num):\n21: primes.append(num)\n22: return primes\n23: \n24: def main():\n25: \"\"\"Main function to demonstrate prime number generation.\"\"\"\n26: limit = 100\n27: prime_list = get_primes(limit)\n28: print(f\"Prime numbers up to {limit}:\")\n29: print(prime_list)\n30: print(f\"Found {len(prime_list)} prime numbers.\")\n31: \n32: if __name__ == \"__main__\":\n33: main()"}]}])
줄 번호
위 예시에서 view 도구 결과에는 각 줄 앞에 줄 번호가 붙은 파일 내용이 포함되어 있습니다(예: “1: def is_prime(n):”). 줄 번호는 필수는 아니지만, 특정 파일 섹션을 검사하기 위한 view_range 매개변수와 정확한 위치에 내용을 추가하기 위한 insert_line 매개변수를 성공적으로 사용하는 데 필수적입니다.
Claude는 구문 오류를 식별하고 str_replace 명령을 사용하여 수정할 것입니다:
{"id":"msg_01VwXyZAbCdEfGhIjKlMnO","model":"claude-opus-4-20250514","stop_reason":"tool_use","role":"assistant","content":[{"type":"text","text":"I found the syntax error in your primes.py file. In the `get_primes` function, there is a missing colon (:) at the end of the for loop line. Let me fix that for you."},{"type":"tool_use","id":"toolu_01PqRsTuVwXyZAbCdEfGh","name":"str_replace_based_edit_tool","input":{"command":"str_replace","path":"primes.py","old_str":" for num in range(2, limit + 1)","new_str":" for num in range(2, limit + 1):"}}]}
그런 다음 애플리케이션은 편집을 수행하고 결과를 반환해야 합니다:
response = client.messages.create( model="claude-opus-4-20250514", max_tokens=1024, tools=[{"type":"text_editor_20250429","name":"str_replace_based_edit_tool"}], messages=[# 이전 메시지들...{"role":"assistant","content":[{"type":"text","text":"I found the syntax error in your primes.py file. In the `get_primes` function, there is a missing colon (:) at the end of the for loop line. Let me fix that for you."},{"type":"tool_use","id":"toolu_01PqRsTuVwXyZAbCdEfGh","name":"str_replace_based_edit_tool","input":{"command":"str_replace","path":"primes.py","old_str":" for num in range(2, limit + 1)","new_str":" for num in range(2, limit + 1):"}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_01PqRsTuVwXyZAbCdEfGh","content":"Successfully replaced text at exactly one location."}]}])
마지막으로, Claude는 수정에 대한 완전한 설명을 제공할 것입니다:
{"id":"msg_01IjKlMnOpQrStUvWxYzAb","model":"claude-opus-4-20250514","stop_reason":"end_turn","role":"assistant","content":[{"type":"text","text":"I've fixed the syntax error in your primes.py file. The issue was in the `get_primes` function at line 19. There was a missing colon (:) at the end of the for loop line.\n\nHere's what I changed:\n\nFrom:\n```python\nfor num in range(2, limit + 1)\n```\n\nTo:\n```python\nfor num in range(2, limit + 1):\n```\n\nIn Python, a colon is required at the end of statements that start a new code block, such as for loops, if statements, function definitions, etc. Without the colon, Python raises a syntax error because it doesn't know where the code block begins.\n\nYour code should now run correctly. The function will properly generate a list of prime numbers up to the specified limit."}]}
이 예시는 Claude 4가 텍스트 에디터 도구를 사용하여 Python 파일의 구문 오류를 수정하는 방법을 보여줍니다.
먼저, 애플리케이션이 Claude에 텍스트 에디터 도구와 구문 오류를 수정하는 프롬프트를 제공합니다:
import anthropicclient = anthropic.Anthropic()response = client.messages.create( model="claude-opus-4-20250514", max_tokens=1024, tools=[{"type":"text_editor_20250429","name":"str_replace_based_edit_tool"}], messages=[{"role":"user","content":"There's a syntax error in my primes.py file. Can you help me fix it?"}])print(response)
Claude는 먼저 텍스트 에디터 도구를 사용하여 파일을 볼 것입니다:
{"id":"msg_01XAbCDeFgHiJkLmNoPQrStU","model":"claude-opus-4-20250514","stop_reason":"tool_use","role":"assistant","content":[{"type":"text","text":"I'll help you fix the syntax error in your primes.py file. First, let me take a look at the file to identify the issue."},{"type":"tool_use","id":"toolu_01AbCdEfGhIjKlMnOpQrStU","name":"str_replace_based_edit_tool","input":{"command":"view","path":"primes.py"}}]}
그런 다음 애플리케이션은 파일을 읽고 그 내용을 Claude에 반환해야 합니다:
response = client.messages.create( model="claude-opus-4-20250514", max_tokens=1024, tools=[{"type":"text_editor_20250429","name":"str_replace_based_edit_tool"}], messages=[{"role":"user","content":"There's a syntax error in my primes.py file. Can you help me fix it?"},{"role":"assistant","content":[{"type":"text","text":"I'll help you fix the syntax error in your primes.py file. First, let me take a look at the file to identify the issue."},{"type":"tool_use","id":"toolu_01AbCdEfGhIjKlMnOpQrStU","name":"str_replace_based_edit_tool","input":{"command":"view","path":"primes.py"}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_01AbCdEfGhIjKlMnOpQrStU","content":"1: def is_prime(n):\n2: \"\"\"Check if a number is prime.\"\"\"\n3: if n <= 1:\n4: return False\n5: if n <= 3:\n6: return True\n7: if n % 2 == 0 or n % 3 == 0:\n8: return False\n9: i = 5\n10: while i * i <= n:\n11: if n % i == 0 or n % (i + 2) == 0:\n12: return False\n13: i += 6\n14: return True\n15: \n16: def get_primes(limit):\n17: \"\"\"Generate a list of prime numbers up to the given limit.\"\"\"\n18: primes = []\n19: for num in range(2, limit + 1)\n20: if is_prime(num):\n21: primes.append(num)\n22: return primes\n23: \n24: def main():\n25: \"\"\"Main function to demonstrate prime number generation.\"\"\"\n26: limit = 100\n27: prime_list = get_primes(limit)\n28: print(f\"Prime numbers up to {limit}:\")\n29: print(prime_list)\n30: print(f\"Found {len(prime_list)} prime numbers.\")\n31: \n32: if __name__ == \"__main__\":\n33: main()"}]}])
줄 번호
위 예시에서 view 도구 결과에는 각 줄 앞에 줄 번호가 붙은 파일 내용이 포함되어 있습니다(예: “1: def is_prime(n):”). 줄 번호는 필수는 아니지만, 특정 파일 섹션을 검사하기 위한 view_range 매개변수와 정확한 위치에 내용을 추가하기 위한 insert_line 매개변수를 성공적으로 사용하는 데 필수적입니다.
Claude는 구문 오류를 식별하고 str_replace 명령을 사용하여 수정할 것입니다:
{"id":"msg_01VwXyZAbCdEfGhIjKlMnO","model":"claude-opus-4-20250514","stop_reason":"tool_use","role":"assistant","content":[{"type":"text","text":"I found the syntax error in your primes.py file. In the `get_primes` function, there is a missing colon (:) at the end of the for loop line. Let me fix that for you."},{"type":"tool_use","id":"toolu_01PqRsTuVwXyZAbCdEfGh","name":"str_replace_based_edit_tool","input":{"command":"str_replace","path":"primes.py","old_str":" for num in range(2, limit + 1)","new_str":" for num in range(2, limit + 1):"}}]}
그런 다음 애플리케이션은 편집을 수행하고 결과를 반환해야 합니다:
response = client.messages.create( model="claude-opus-4-20250514", max_tokens=1024, tools=[{"type":"text_editor_20250429","name":"str_replace_based_edit_tool"}], messages=[# 이전 메시지들...{"role":"assistant","content":[{"type":"text","text":"I found the syntax error in your primes.py file. In the `get_primes` function, there is a missing colon (:) at the end of the for loop line. Let me fix that for you."},{"type":"tool_use","id":"toolu_01PqRsTuVwXyZAbCdEfGh","name":"str_replace_based_edit_tool","input":{"command":"str_replace","path":"primes.py","old_str":" for num in range(2, limit + 1)","new_str":" for num in range(2, limit + 1):"}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_01PqRsTuVwXyZAbCdEfGh","content":"Successfully replaced text at exactly one location."}]}])
마지막으로, Claude는 수정에 대한 완전한 설명을 제공할 것입니다:
{"id":"msg_01IjKlMnOpQrStUvWxYzAb","model":"claude-opus-4-20250514","stop_reason":"end_turn","role":"assistant","content":[{"type":"text","text":"I've fixed the syntax error in your primes.py file. The issue was in the `get_primes` function at line 19. There was a missing colon (:) at the end of the for loop line.\n\nHere's what I changed:\n\nFrom:\n```python\nfor num in range(2, limit + 1)\n```\n\nTo:\n```python\nfor num in range(2, limit + 1):\n```\n\nIn Python, a colon is required at the end of statements that start a new code block, such as for loops, if statements, function definitions, etc. Without the colon, Python raises a syntax error because it doesn't know where the code block begins.\n\nYour code should now run correctly. The function will properly generate a list of prime numbers up to the specified limit."}]}
이 예시는 Claude Sonnet 3.7이 텍스트 에디터 도구를 사용하여 Python 파일의 구문 오류를 수정하는 방법을 보여줍니다.
먼저, 애플리케이션이 Claude에 텍스트 에디터 도구와 구문 오류를 수정하는 프롬프트를 제공합니다:
import anthropicclient = anthropic.Anthropic()response = client.messages.create( model="claude-3-7-sonnet-20250219", max_tokens=1024, tools=[{"type":"text_editor_20250124","name":"str_replace_editor"}], messages=[{"role":"user","content":"There's a syntax error in my primes.py file. Can you help me fix it?"}])print(response)
Claude Sonnet 3.7 예시는 위의 Claude 4 예시와 동일한 형식을 따르며, 동일한 도구 호출과 응답을 사용하지만 text_editor_20250124 도구 유형과 str_replace_editor 이름을 사용합니다.
텍스트 에디터 도구는 스키마가 없는 도구로 구현됩니다. 이 도구를 사용할 때 다른 도구와 같이 입력 스키마를 제공할 필요가 없습니다. 스키마는 Claude의 모델에 내장되어 있으며 수정할 수 없습니다.
도구 유형은 모델 버전에 따라 다릅니다:
Claude 4: type: "text_editor_20250429"
Claude Sonnet 3.7: type: "text_editor_20250124"
Claude Sonnet 3.5: type: "text_editor_20241022"
1
에디터 구현 초기화
파일 읽기, 쓰기 및 수정과 같은 파일 작업을 처리하는 헬퍼 함수를 만듭니다. 실수로부터 복구하기 위한 백업 기능 구현을 고려하세요.
2
에디터 도구 호출 처리
명령 유형에 따라 Claude의 도구 호출을 처리하는 함수를 만듭니다:
defhandle_editor_tool(tool_call, model_version): input_params = tool_call.input command = input_params.get('command','') file_path = input_params.get('path','')if command =='view':# 파일 내용을 읽고 반환passelif command =='str_replace':# 파일에서 텍스트 대체passelif command =='create':# 새 파일 생성passelif command =='insert':# 위치에 텍스트 삽입passelif command =='undo_edit':# Claude 4 모델인지 확인if'str_replace_based_edit_tool'in model_version:return{"error":"undo_edit command is not supported in Claude 4"}# Claude 3.7/3.5용 백업에서 복원pass
3
보안 조치 구현
검증 및 보안 검사 추가:
디렉토리 순회를 방지하기 위한 파일 경로 검증
변경 전 백업 생성
오류를 우아하게 처리
권한 검사 구현
4
Claude의 응답 처리
Claude의 응답에서 도구 호출을 추출하고 처리:
# Claude의 응답에서 도구 사용 처리for content in response.content:if content.type=="tool_use":# 명령에 따라 도구 실행 result = handle_editor_tool(content)# Claude에 결과 반환 tool_result ={"type":"tool_result","tool_use_id": content.id,"content": result}
텍스트 에디터 도구를 구현할 때 다음 사항을 염두에 두세요:
보안: 이 도구는 로컬 파일 시스템에 액세스할 수 있으므로 적절한 보안 조치를 구현하세요.
백업: 중요한 파일을 편집하기 전에 항상 백업을 생성하세요.
검증: 의도하지 않은 변경을 방지하기 위해 모든 입력을 검증하세요.
고유 일치: 의도하지 않은 편집을 방지하기 위해 대체가 정확히 한 위치와 일치하는지 확인하세요.
텍스트 에디터 도구를 사용할 때 다양한 오류가 발생할 수 있습니다. 다음은 이를 처리하는 방법에 대한 지침입니다:
Claude가 존재하지 않는 파일을 보거나 수정하려고 하면 tool_result에 적절한 오류 메시지를 반환합니다:
{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_01A09q90qw90lq917835lq9","content":"Error: File not found","is_error":true}]}
Claude의 str_replace 명령이 파일에서 여러 위치와 일치하는 경우 적절한 오류 메시지를 반환합니다:
{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_01A09q90qw90lq917835lq9","content":"Error: Found 3 matches for replacement text. Please provide more context to make a unique match.","is_error":true}]}
Claude의 str_replace 명령이 파일에서 텍스트와 일치하지 않는 경우 적절한 오류 메시지를 반환합니다:
{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_01A09q90qw90lq917835lq9","content":"Error: No match found for replacement. Please check your text and try again.","is_error":true}]}
파일 생성, 읽기 또는 수정에 권한 문제가 있는 경우 적절한 오류 메시지를 반환합니다:
{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_01A09q90qw90lq917835lq9","content":"Error: Permission denied. Cannot write to file.","is_error":true}]}
Claude에게 코드를 수정하거나 변경하도록 요청할 때, 어떤 파일을 검사해야 하는지 또는 어떤 문제를 해결해야 하는지에 대해 구체적으로 명시하세요. 명확한 컨텍스트는 Claude가 올바른 파일을 식별하고 적절한 변경을 하는 데 도움이 됩니다.
덜 유용한 프롬프트: “내 코드를 수정해 줄 수 있나요?”
더 나은 프롬프트: “primes.py 파일에 실행을 방해하는 구문 오류가 있습니다. 이를 수정해 줄 수 있나요?”
특히 여러 파일이나 다른 디렉토리에 있는 파일로 작업하는 경우 필요할 때 파일 경로를 명확하게 지정하세요.
덜 유용한 프롬프트: “내 헬퍼 파일을 검토해 주세요”
더 나은 프롬프트: “utils/helpers.py 파일에 성능 문제가 있는지 확인해 줄 수 있나요?”
특히 중요하거나 프로덕션 코드의 경우, Claude가 편집하기 전에 파일의 복사본을 만드는 백업 시스템을 애플리케이션에 구현하세요.
defbackup_file(file_path):"""편집 전 파일 백업 생성.""" backup_path =f"{file_path}.backup"if os.path.exists(file_path):withopen(file_path,'r')as src,open(backup_path,'w')as dst: dst.write(src.read())
str_replace 명령은 대체할 텍스트와 정확히 일치해야 합니다. 애플리케이션은 이전 텍스트와 정확히 한 번 일치하는지 확인하거나 적절한 오류 메시지를 제공해야 합니다.
defsafe_replace(file_path, old_text, new_text):"""정확히 하나의 일치 항목이 있는 경우에만 텍스트 대체."""withopen(file_path,'r')as f: content = f.read() count = content.count(old_text)if count ==0:return"Error: No match found"elif count >1:returnf"Error: Found {count} matches"else: new_content = content.replace(old_text, new_text)withopen(file_path,'w')as f: f.write(new_content)return"Successfully replaced text"
Claude가 파일을 변경한 후, 테스트를 실행하거나 코드가 여전히 예상대로 작동하는지 확인하여 변경 사항을 검증하세요.
defverify_changes(file_path):"""변경 후 테스트 또는 검사 실행."""try:# Python 파일의 경우 구문 오류 확인if file_path.endswith('.py'):import astwithopen(file_path,'r')as f: ast.parse(f.read())return"Syntax check passed"except Exception as e:returnf"Verification failed: {str(e)}"