sdfxa commited on
Commit
ef55883
·
verified ·
1 Parent(s): f5cd42d

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. x_node.py +149 -0
x_node.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import os
3
+ import sys
4
+ import json
5
+ import shutil
6
+ import subprocess
7
+ import platform
8
+ import getpass
9
+ import datetime
10
+ from typing import Dict, Any
11
+ import psutil
12
+
13
+ #!/usr/bin/env python3
14
+ """
15
+ x_node.py
16
+
17
+ 获取全部环境变量、当前进程信息,并检测 curl、wget 是否可调用(并尝试获取版本信息)。
18
+ 输出 JSON 到 stdout,兼容 Linux/macOS/Windows。尽量不依赖第三方库,若安装 psutil 会提供更详细信息。
19
+ """
20
+
21
+
22
+ # Try to import psutil if available for richer process info
23
+ try:
24
+ except Exception:
25
+ psutil = None # type: ignore
26
+
27
+
28
+ def get_env_vars() -> Dict[str, str]:
29
+ """Return all environment variables as a dict."""
30
+ return dict(os.environ)
31
+
32
+
33
+ def safe_run_version(cmd: list[str], timeout: float = 3.0) -> Dict[str, Any]:
34
+ """Try to run `cmd --version` (cmd is full command list) and capture output."""
35
+ try:
36
+ p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout, check=False)
37
+ out = p.stdout.decode(errors="replace").strip()
38
+ # For long output, keep first few lines
39
+ short_out = "\n".join(out.splitlines()[:5])
40
+ return {"ok": True, "rc": p.returncode, "output": short_out}
41
+ except FileNotFoundError:
42
+ return {"ok": False, "error": "not found"}
43
+ except subprocess.TimeoutExpired:
44
+ return {"ok": False, "error": "timeout"}
45
+ except Exception as e:
46
+ return {"ok": False, "error": str(e)}
47
+
48
+
49
+ def check_tools(tools: list[str]) -> Dict[str, Dict[str, Any]]:
50
+ """Check whether tools are callable (in PATH) and try to get version."""
51
+ results: Dict[str, Dict[str, Any]] = {}
52
+ for t in tools:
53
+ path = shutil.which(t)
54
+ info: Dict[str, Any] = {"path": path, "callable": bool(path)}
55
+ if path:
56
+ # Prefer conventional --version, fallback to -V, -v
57
+ for flag in ("--version", "-V", "-v"):
58
+ res = safe_run_version([t, flag])
59
+ if res.get("ok") and res.get("output"):
60
+ info["version_cmd"] = flag
61
+ info["version_output"] = res.get("output")
62
+ break
63
+ else:
64
+ # Try running with no args to see if there's any output
65
+ res = safe_run_version([t])
66
+ if res.get("ok"):
67
+ info["version_cmd"] = None
68
+ info["version_output"] = res.get("output")
69
+ else:
70
+ info["version_error"] = res.get("error")
71
+ results[t] = info
72
+ return results
73
+
74
+
75
+ def get_process_info() -> Dict[str, Any]:
76
+ """Collect basic process information. If psutil is available, include richer info."""
77
+ info: Dict[str, Any] = {}
78
+ info["platform"] = platform.system()
79
+ info["platform_release"] = platform.release()
80
+ info["platform_version"] = platform.version()
81
+ info["machine"] = platform.machine()
82
+ info["processor"] = platform.processor()
83
+ info["python_version"] = platform.python_version()
84
+ info["python_executable"] = sys.executable
85
+ info["argv"] = sys.argv
86
+ info["cwd"] = os.getcwd()
87
+ info["pid"] = os.getpid()
88
+ # ppid is available on most platforms
89
+ try:
90
+ info["ppid"] = os.getppid()
91
+ except Exception:
92
+ info["ppid"] = None
93
+ info["user"] = getpass.getuser()
94
+
95
+ # Add Unix-specific ids if available
96
+ if hasattr(os, "getuid"):
97
+ try:
98
+ info["uid"] = os.getuid()
99
+ info["gid"] = os.getgid()
100
+ if hasattr(os, "geteuid"):
101
+ info["euid"] = os.geteuid()
102
+ if hasattr(os, "getegid"):
103
+ info["egid"] = os.getegid()
104
+ except Exception:
105
+ pass
106
+
107
+ # Try using psutil for richer details
108
+ if psutil:
109
+ try:
110
+ p = psutil.Process(info["pid"])
111
+ with p.oneshot():
112
+ info["exe"] = p.exe()
113
+ info["cmdline"] = p.cmdline()
114
+ info["create_time"] = datetime.datetime.fromtimestamp(p.create_time()).isoformat()
115
+ info["cpu_percent"] = p.cpu_percent(interval=0.1)
116
+ mem = p.memory_info()
117
+ info["memory_rss"] = mem.rss
118
+ info["memory_vms"] = mem.vms
119
+ info["num_threads"] = p.num_threads()
120
+ try:
121
+ info["open_files"] = [f.path for f in p.open_files()]
122
+ except Exception:
123
+ info["open_files"] = None
124
+ try:
125
+ info["connections"] = [str(c) for c in p.connections()]
126
+ except Exception:
127
+ info["connections"] = None
128
+ except Exception:
129
+ # Fall back to minimal info already present
130
+ pass
131
+ else:
132
+ # Fallback values
133
+ info["exe"] = sys.executable
134
+ info["cmdline"] = sys.argv
135
+ info["create_time"] = None
136
+ return info
137
+
138
+
139
+ def main() -> int:
140
+ env = get_env_vars()
141
+ process = get_process_info()
142
+ tools = check_tools(["curl", "wget"])
143
+ result = {"env": env, "process": process, "tools": tools}
144
+ # Print JSON
145
+ print(json.dumps(result, indent=2, ensure_ascii=False))
146
+ return 0
147
+
148
+
149
+ main()