Files
Document_Translator/start_celery.py
2025-09-02 16:47:16 +08:00

82 lines
2.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
啟動 Celery Worker 的輔助腳本
"""
import sys
import os
# Fix encoding for Windows console
if sys.stdout.encoding != 'utf-8':
sys.stdout.reconfigure(encoding='utf-8')
if sys.stderr.encoding != 'utf-8':
sys.stderr.reconfigure(encoding='utf-8')
# 將 app 目錄加入 sys.path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'app'))
def start_celery_worker():
"""啟動 Celery Worker"""
print("正在啟動 Celery Worker...")
# 設置環境變數
os.environ.setdefault('FLASK_ENV', 'development')
# 導入應用
from app import create_app
app = create_app()
print(f"Flask 應用已創建: {app}")
print(f"Celery 實例: {app.celery}")
# 啟動 Celery Worker
# Windows 需要使用 --pool=solo 參數
print("正在啟動 Celery WorkerWindows 模式)...")
# 使用 subprocess 啟動 celery worker
import subprocess
cmd = [
sys.executable, '-m', 'celery',
'-A', 'app.celery',
'worker',
'--loglevel=info',
'--pool=solo'
]
print(f"執行命令: {' '.join(cmd)}")
try:
# 切換到正確的目錄
os.chdir(os.path.dirname(__file__))
# 啟動進程
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
encoding='utf-8',
bufsize=1,
universal_newlines=True
)
print("Celery Worker 已啟動PID:", process.pid)
print("正在監控輸出...")
# 即時顯示輸出
for line in iter(process.stdout.readline, ''):
print(line.rstrip())
except KeyboardInterrupt:
print("\n收到中斷信號,正在停止 Celery Worker...")
if 'process' in locals():
process.terminate()
sys.exit(0)
except Exception as e:
print(f"啟動 Celery Worker 時發生錯誤: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
start_celery_worker()