맥에서 자주 쓰는 파이썬 스크립트를 매번 터미널 열어서 실행하는 게 번거로우신가요? Raycast를 활용하면 단축키 하나로 파이썬 코드를 실행할 수 있어요.
Script Command로 5분 만에 파이썬 실행 버튼 만들기
가장 빠른 방법은 Script Command를 활용하는 거예요. 먼저 실행하고 싶은 파이썬 파일을 만들어볼게요.
# ~/scripts/daily_report.py
import datetime
import requests
def generate_report():
today = datetime.datetime.now().strftime("%Y-%m-%d")
print(f"📊 {today} 일일 리포트 생성 완료!")
# 여기에 실제 작업 코드 추가
# API 호출, 데이터 처리, 파일 생성 등
if __name__ == "__main__":
generate_report()
이제 이 파이썬 코드를 Raycast에서 실행할 Shell 스크립트를 만들어요.
#!/bin/bash
# Required parameters:
# @raycast.schemaVersion 1
# @raycast.title Daily Report Generator
# @raycast.mode compact
# Optional parameters:
# @raycast.icon 📊
# @raycast.packageName Python Scripts
python3 ~/scripts/daily_report.py
파일을 daily_report.sh 로 저장하고 실행 권한을 부여해요.
chmod +x daily_report.sh
Raycast를 열고 Extensions → Script Commands로 이동해서 방금 만든 스크립트를 추가하면 끝이에요. 이제 Raycast에서 Daily Report를 검색하면 바로 실행할 수 있어요.
입력값을 받는 스크립트 만들기
사용자 입력을 받아서 처리하는 스크립트도 간단하게 만들 수 있어요.
#!/bin/bash
# @raycast.schemaVersion 1
# @raycast.title Create Python Project
# @raycast.mode compact
# @raycast.argument1 { "type": "text", "placeholder": "Project name" }
project_name=$1
# 프로젝트 디렉토리 생성
mkdir -p ~/projects/"$project_name"
cd ~/projects/"$project_name"
# 가상환경 설정
python3 -m venv venv
source venv/bin/activate
# 기본 파일 생성
cat > main.py << EOF
#!/usr/bin/env python3
"""
$project_name - Created on $(date +%Y-%m-%d)
"""
def main():
print("Hello from $project_name!")
if __name__ == "__main__":
main()
EOF
# requirements.txt 생성
touch requirements.txt
touch README.md
echo "✅ Python project '$project_name' created successfully!"
커스텀 확장으로 고급 기능 구현하기
더 복잡한 UI나 상호작용이 필요하다면 TypeScript로 커스텀 확장을 개발할 수 있어요. Node.js의 child_process를 사용해서 파이썬 스크립트를 실행하는 방식이에요.
import { Action, ActionPanel, List, showToast, Toast } from "@raycast/api";
import { exec } from "child_process";
import { promisify } from "util";
const execAsync = promisify(exec);
export default function Command() {
const runPythonScript = async (scriptName: string) => {
try {
const { stdout } = await execAsync(`python3 ~/scripts/${scriptName}`);
await showToast({
style: Toast.Style.Success,
title: "Script Executed",
message: stdout.trim()
});
} catch (error) {
await showToast({
style: Toast.Style.Failure,
title: "Execution Failed",
message: error.message
});
}
};
return (
<List>
<List.Item
title="Generate Daily Report"
subtitle="Creates today's report"
actions={
<ActionPanel>
<Action title="Run" onAction={() => runPythonScript("daily_report.py")} />
</ActionPanel>
}
/>
</List>
);
}
실전 활용 예시: 자동화 스크립트 모음
자주 사용하는 파이썬 작업들을 Raycast 버튼으로 만들어보면 업무 효율이 크게 올라가요.
클립보드 데이터 처리기
# clipboard_processor.py
import subprocess
import json
def get_clipboard():
return subprocess.check_output(['pbpaste']).decode('utf-8')
def process_json():
try:
data = get_clipboard()
parsed = json.loads(data)
formatted = json.dumps(parsed, indent=2, ensure_ascii=False)
# 다시 클립보드에 복사
process = subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE)
process.communicate(formatted.encode('utf-8'))
print("✅ JSON 포맷팅 완료!")
except json.JSONDecodeError:
print("❌ 클립보드의 내용이 유효한 JSON이 아니에요")
if __name__ == "__main__":
process_json()
CSV 파일 빠른 분석기
# quick_csv_analyzer.py
import pandas as pd
import sys
from pathlib import Path
def analyze_csv(filepath):
try:
df = pd.read_csv(filepath)
print(f"📊 파일: {Path(filepath).name}")
print(f"행 개수: {len(df):,}")
print(f"열 개수: {len(df.columns)}")
print(f"\n컬럼 목록:")
for col in df.columns:
print(f" - {col} ({df[col].dtype})")
print(f"\n결측치 정보:")
missing = df.isnull().sum()
for col, count in missing[missing > 0].items():
print(f" - {col}: {count}개")
except Exception as e:
print(f"❌ 오류 발생: {e}")
if __name__ == "__main__":
if len(sys.argv) > 1:
analyze_csv(sys.argv[1])
else:
print("사용법: python quick_csv_analyzer.py [파일경로]")
안정적인 스크립트 구조 만들기
파이썬 스크립트를 Raycast와 연동할 때는 에러 처리와 로깅이 중요해요. 기본 템플릿을 만들어두면 유용해요.
#!/usr/bin/env python3
import argparse
import logging
import sys
from pathlib import Path
# 로깅 설정
log_file = Path.home() / "raycast_scripts.log"
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(log_file),
logging.StreamHandler(sys.stdout)
]
)
logger = logging.getLogger(__name__)
def main(args):
try:
logger.info(f"스크립트 시작: {args}")
# 여기에 실제 작업 코드
result = process_task(args.input)
print(f"✅ 작업 완료: {result}")
logger.info(f"작업 성공: {result}")
except Exception as e:
error_msg = f"❌ 오류 발생: {str(e)}"
print(error_msg)
logger.error(error_msg, exc_info=True)
sys.exit(1)
def process_task(input_data):
# 실제 작업 로직
return f"Processed: {input_data}"
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Raycast Python Script")
parser.add_argument("--input", type=str, help="입력 데이터")
args = parser.parse_args()
main(args)
주의사항과 최적화 팁
맥에서 파이썬 스크립트를 자동화할 때 자주 마주치는 문제들이 있어요.
파이썬 경로 문제 해결
시스템 파이썬과 Homebrew로 설치한 파이썬이 섞이면 모듈 에러가 발생해요. Script Command에서는 절대 경로를 명시하는 게 안전해요.
#!/bin/bash
# 가상환경 활성화 후 실행
source ~/projects/myproject/venv/bin/activate
python ~/projects/myproject/script.py
환경 변수 처리
Raycast는 터미널과 다른 환경에서 실행되므로 . zshrc의 환경 변수를 못 읽을 수 있어요.
import os
import sys
# 필요한 경로 직접 추가
sys.path.insert(0, '/Users/username/my_modules')
# 환경 변수 설정
os.environ['API_KEY'] = 'your-api-key'
실행 시간 최적화
Raycast는 빠른 실행을 중시하므로 무거운 import는 필요할 때만 해요.
def process_data():
# pandas가 필요한 경우에만 import
import pandas as pd
df = pd.read_csv('data.csv')
return df.describe()
Script Command 방식은 설정이 간단해서 대부분의 경우 충분해요. 복잡한 UI가 필요하거나 여러 스크립트를 관리하고 싶다면 커스텀 확장 개발을 고려해보세요.
가장 중요한 건 자주 사용하는 작업을 찾아내고, 그것을 자동화하는 거예요. 하루에 5번씩 실행하던 명령어를 단축키 하나로 만들면 그 편리함은 직접 경험해봐야 알 수 있어요.