Develop
[Python] Subprocess, 터미널 명령어 활용 방법
너드나무
2024. 5. 3. 20:20
반응형
서론
일일 작업한 개발 이력에 대해 정리 및 회고를 할 방법을 간단한 스크립트를 활용하여 일자 관리를 해보려고 한다.
다만, 활용한 개발 도구에 대해 API를 모두 지원하지 않으므로 설치 후 터미널을 활용하는 방법을 응용하기로 해본다.
Git 관련 이력을 정리하는 부분을 MVP로 점진적으로 활용 방법을 늘려보도록 한다.
개요
- python subprocess module
- 모듈명처럼 서브 프로세스를 생성하여, 작업한 내용을 메모리에 저장하고 활용할 수 있게 만들어주는 기능을 제공한다.
- 운영체제론을 공부하면서 접할 수 있는 공유 메모리와 세마포어 활용 부분을 연관지어 고민해보아도 좋은 모듈이다.
https://docs.python.org/ko/3/library/subprocess.html
subprocess — Subprocess management
Source code: Lib/subprocess.py The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace seve...
docs.python.org
- diff
- 두 개의 파일 간 차이에 대한 정보를 출력하는 파일 비교 유틸리티
- git에서는 이전 commit에 반영된 파일과 비교하여 추가/삭제에 대한 부분을 보여주는 도구로 활용된다.
https://ko.wikipedia.org/wiki/Diff
diff - 위키백과, 우리 모두의 백과사전
위키백과, 우리 모두의 백과사전. 컴퓨터에서 diff는 두 개의 파일 간 차이에 대한 정보를 출력하는 파일 비교 유틸리티이다. 일반적으로 하나의 파일 버전과 동일한 파일의 다른 버전 간의 변경
ko.wikipedia.org
적용
- 전체 코드
- 레포지토리를 설정하여 해당 repo의 이력을 볼 수 있게 준비
- 금일 github 작업 이력(commit)을 추출하여 diff를 통해 코드 단계에서 작업 이력 보여주기
- 출력 결과는 파일로 저장하여 이력을 일자별로 정리할 수 있도록 개발
import subprocess, os, datetime
def get_commit_diff(commit_hash):
# git show 명령어 실행하여 커밋의 diff 내용 가져오기
git_show_command = f"git show --pretty {commit_hash}"
try:
result = subprocess.check_output(git_show_command, shell=True, encoding='utf-8')
return result
except subprocess.CalledProcessError:
print(f"Error: Git command failed for commit hash: {commit_hash}")
return ""
def get_today_commits_with_diff():
# 현재 날짜 가져오기
today = datetime.datetime.now().strftime("%Y.%m.%d")
# git log 명령어 실행하여 오늘의 커밋 이력 가져오기
git_log_command = f"git log --pretty=format:'%h' --author=$(git config user.name) --since='{today} 00:00:00' --until='{today} 23:59:59' --reverse"
try:
commit_hashes = subprocess.check_output(git_log_command, shell=True, encoding='utf-8').splitlines()
commits_with_diff = {}
for commit_hash in commit_hashes:
diff = get_commit_diff(commit_hash)
if diff:
commits_with_diff[commit_hash] = diff
return commits_with_diff
except subprocess.CalledProcessError:
print("Error: Git command failed.")
return {}
def save_commits_with_diff_to_file(commits_with_diff):
today = datetime.datetime.now().strftime("%Y.%m.%d")
filename = f"{today}.txt"
with open(filename, "w") as file:
for commit_hash, diff_content in commits_with_diff.items():
file.write(f"Commit Hash: {commit_hash}\n")
file.write("Diff content:\n")
file.write(diff_content)
file.write("\n\n")
print(f"Saved commits with diff to {filename}")
if __name__ == "__main__":
repo_path = "Repository Directory Path"
os.chdir(repo_path)
today_commits_with_diff = get_today_commits_with_diff()
if today_commits_with_diff:
save_commits_with_diff_to_file(today_commits_with_diff)
else:
print("No commits found for today.")
- subporcess 동작
- check_output : string 형태의 스크립트를 기반으로 실행할 주체와 인코딩을 설정하여 splitlines로 List 저장
- 아래 코드는 git log에 대한 결과값을 commit_hashes에 저장하고,
- commit hash를 기반으로 해당 diff 데이터를 추출하여 반환하는 목적을 가진다.
def get_today_commits_with_diff():
# 현재 날짜 가져오기
today = datetime.datetime.now().strftime("%Y.%m.%d")
# git log 명령어 실행하여 오늘의 커밋 이력 가져오기
git_log_command = f"git log --pretty=format:'%h' --author=$(git config user.name) --since='{today} 00:00:00' --until='{today} 23:59:59' --reverse"
try:
commit_hashes = subprocess.check_output(git_log_command, shell=True, encoding='utf-8').splitlines()
commits_with_diff = {}
for commit_hash in commit_hashes:
diff = get_commit_diff(commit_hash)
if diff:
commits_with_diff[commit_hash] = diff
return commits_with_diff
except subprocess.CalledProcessError:
print("Error: Git command failed.")
return {}
결론
- subprocess는 동작시키는 운영체제의 특징을 상속받는다.
- Windows에서는 가능한 명령어가 Mac, Linux에서는 안되는데요..?
- ipconfig, ifconfg, ls, dir 등 해당 운영체제에서 사용하는 명령어를 확인해보자.
- 간단한 스크립트는 생성형 AI가 최고...
- 요구사항이 명확하면 AI를 통해 개발 기간을 급격히 단축할 수 있다.
- PoC 개념으로 접근하고, 디테일 코드를 조정하면 대부분 신속하게 개발이 가능했다.
참고 및 인용 출처
- 안윤호. [하이큐텍]. (2001.07). 공유 메모리와 세마포어 활용.
- Python. [3.12.3]. (2024.03). subprocess. https://docs.python.org/3/library/subprocess.html.
- 위키백과. [위키백과]. (2022.08). diff. https://ko.wikipedia.org/wiki/Diff.
728x90
반응형