79 lines
3.3 KiB
Python
79 lines
3.3 KiB
Python
"""独立任务入口。刷新界面或切换页面不会重新启动计算。"""
|
||
import asyncio
|
||
import json
|
||
from pathlib import Path
|
||
import sys
|
||
import time
|
||
|
||
from .tasks import write_json
|
||
from marketgrid.config import TaskCancelled
|
||
|
||
|
||
def run(directory, credentials):
|
||
directory = Path(directory)
|
||
path = directory / "state.json"
|
||
state = json.loads(path.read_text(encoding="utf-8"))
|
||
state.update(status="running", message="开始处理", started=time.time())
|
||
write_json(path, state)
|
||
def progress(done, total, message, **extra):
|
||
state.update(done=done, total=total, message=message, **extra)
|
||
write_json(path, state)
|
||
def stopping():
|
||
return (directory / "stop").exists()
|
||
try:
|
||
if stopping():
|
||
raise TaskCancelled("启动前已停止。")
|
||
if state["kind"] == "market":
|
||
from marketgrid.pipeline import main
|
||
settings = {**state["params"], "OUTPUT_DIR": state["output"],
|
||
"STOP_FILE": str(directory / "stop"), "OVERWRITE": True, "LIMIT": None}
|
||
main(settings, progress)
|
||
else:
|
||
import GetNRBuildingsData as query
|
||
for key, value in state["params"].items():
|
||
setattr(query, key, value)
|
||
for key in ("URL", "COOKIES", "REFERER"):
|
||
if key in credentials:
|
||
setattr(query, key, credentials[key])
|
||
query.OUTPUT_CSV = Path(state["output"]) / "NRBuildingsData.csv"
|
||
last = 0
|
||
def report(counts):
|
||
nonlocal last
|
||
now = time.monotonic()
|
||
state["counts"] = counts
|
||
state["done"] = counts["查询坐标"]
|
||
if now - last >= 0.5:
|
||
progress(counts["查询坐标"], query.LIMIT or 0, "正在查询楼宇", counts=counts)
|
||
last = now
|
||
result = asyncio.run(query.async_main(handle_signals=False, should_stop=stopping, progress=report))
|
||
if stopping():
|
||
raise TaskCancelled("已停止领取新坐标,进行中的查询和写入已完成。")
|
||
if result:
|
||
raise ValueError("部分查询失败或认证失效,已保存返回结果,请查看日志和 CSV 状态列。")
|
||
state["total"] = state["done"]
|
||
state.update(status="success", message="处理完成")
|
||
except TaskCancelled as error:
|
||
state.update(status="cancelled", message=str(error))
|
||
except Exception as error:
|
||
# 不输出堆栈局部变量;外部输入中的凭据也不进入日志。
|
||
chain = []
|
||
current = error
|
||
while current is not None:
|
||
chain.append(str(current))
|
||
current = current.__cause__
|
||
message = ":".join(chain)
|
||
for value in credentials.values():
|
||
if value:
|
||
message = message.replace(value, "[已隐藏]")
|
||
print(f"任务失败:{message}", flush=True)
|
||
state.update(status="failed", message=message)
|
||
finally:
|
||
state["finished"] = time.time()
|
||
write_json(path, state)
|
||
return 0 if state["status"] in {"success", "cancelled"} else 1
|
||
|
||
|
||
if __name__ == "__main__":
|
||
credentials = json.loads(sys.stdin.buffer.read().decode("utf-8"))
|
||
raise SystemExit(run(sys.argv[1], credentials))
|