47 lines
1.8 KiB
Python
47 lines
1.8 KiB
Python
"""查找旧版部署或外部启动的本机 djev,供桌面端正常退出时核对并回收进程。"""
|
||
import json
|
||
import sys
|
||
from datetime import datetime, timezone
|
||
from pathlib import Path
|
||
|
||
import psutil
|
||
|
||
|
||
def service_arguments(argv):
|
||
"""仅识别两个已发布的 Python 启动入口,排除 probe、status 和其他 Python 程序。"""
|
||
args = argv[1:]
|
||
if args[:1] == ["-u"]:
|
||
args = args[1:]
|
||
if not args:
|
||
return []
|
||
script = Path(args[0]).name
|
||
if script == "start_d3_lite_local.py":
|
||
return args[1:]
|
||
if script == "d3nano-service.py" and args[1:2] == ["serve"]:
|
||
return args[2:]
|
||
return []
|
||
|
||
|
||
def find_services(root, port):
|
||
"""匹配启动目录与端口,包括尚未监听的模型。切换过目录时只接管实际监听该端口的服务。"""
|
||
matches = []
|
||
for proc in psutil.process_iter(["name"]):
|
||
if not (proc.info["name"] or "").lower().startswith("python"):
|
||
continue
|
||
try:
|
||
args = service_arguments(proc.cmdline())
|
||
if "--port" not in args or args[args.index("--port") + 1] != str(port):
|
||
continue
|
||
same_root = "--root" in args and Path(args[args.index("--root") + 1]).resolve() == root
|
||
if not same_root and not any(c.status == psutil.CONN_LISTEN and c.laddr.port == port
|
||
and c.laddr.ip in ("127.0.0.1", "::1") for c in proc.net_connections("tcp")):
|
||
continue
|
||
matches.append(dict(Pid=proc.pid, StartedUtc=datetime.fromtimestamp(proc.create_time(), timezone.utc).isoformat().replace("+00:00", "Z")))
|
||
except (psutil.NoSuchProcess, psutil.AccessDenied, IndexError):
|
||
continue
|
||
return matches
|
||
|
||
|
||
if __name__ == "__main__":
|
||
print(json.dumps(find_services(Path(sys.argv[1]).resolve(), int(sys.argv[2]))))
|