Skip to content

Commit 89cfc96

Browse files
Create hardware_info.py
1 parent 6ac7164 commit 89cfc96

1 file changed

Lines changed: 205 additions & 0 deletions

File tree

.github/workflows/hardware_info.py

Lines changed: 205 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,205 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Script to get CPU and RAM information using multiple methods
4+
Compatible with GitHub Actions workflows
5+
"""
6+
7+
import os
8+
import platform
9+
import subprocess
10+
import sys
11+
import json
12+
13+
class HardwareInfo:
14+
def __init__(self):
15+
self.system = platform.system().lower()
16+
17+
def get_cpu_info_method1(self):
18+
"""Method 1: Using platform and os modules"""
19+
try:
20+
cpu_info = {
21+
"architecture": platform.architecture()[0],
22+
"machine": platform.machine(),
23+
"processor": platform.processor(),
24+
"system": platform.system(),
25+
"cpu_count": os.cpu_count(),
26+
"platform": platform.platform()
27+
}
28+
return cpu_info
29+
except Exception as e:
30+
return {"error": f"Method 1 failed: {str(e)}"}
31+
32+
def get_cpu_info_method2(self):
33+
"""Method 2: Using /proc/cpuinfo on Linux systems"""
34+
try:
35+
if self.system != "linux":
36+
return {"error": "Method 2 only works on Linux systems"}
37+
38+
cpu_info = {}
39+
with open('/proc/cpuinfo', 'r') as f:
40+
for line in f:
41+
if line.strip():
42+
if ':' in line:
43+
key, value = line.split(':', 1)
44+
cpu_info[key.strip()] = value.strip()
45+
46+
# Extract key information
47+
result = {
48+
"model_name": cpu_info.get('model name', 'Unknown'),
49+
"cores": int(cpu_info.get('cpu cores', 1)),
50+
"threads": len([k for k in cpu_info.keys() if k.startswith('processor')]),
51+
"vendor_id": cpu_info.get('vendor_id', 'Unknown')
52+
}
53+
return result
54+
except Exception as e:
55+
return {"error": f"Method 2 failed: {str(e)}"}
56+
57+
def get_cpu_info_method3(self):
58+
"""Method 3: Using subprocess and system commands"""
59+
try:
60+
if self.system == "linux":
61+
# Get CPU info using lscpu
62+
result = subprocess.run(['lscpu'], capture_output=True, text=True, timeout=10)
63+
if result.returncode == 0:
64+
cpu_info = {}
65+
for line in result.stdout.split('\n'):
66+
if ':' in line:
67+
key, value = line.split(':', 1)
68+
cpu_info[key.strip()] = value.strip()
69+
return cpu_info
70+
elif self.system == "darwin": # macOS
71+
result = subprocess.run(['sysctl', '-n', 'machdep.cpu.brand_string'],
72+
capture_output=True, text=True, timeout=10)
73+
if result.returncode == 0:
74+
return {"cpu_model": result.stdout.strip()}
75+
76+
return {"error": f"Method 3 not supported on {self.system}"}
77+
except Exception as e:
78+
return {"error": f"Method 3 failed: {str(e)}"}
79+
80+
def get_ram_info_method1(self):
81+
"""Method 1: Using /proc/meminfo on Linux"""
82+
try:
83+
if self.system != "linux":
84+
return {"error": "Method 1 only works on Linux systems"}
85+
86+
mem_info = {}
87+
with open('/proc/meminfo', 'r') as f:
88+
for line in f:
89+
if ':' in line:
90+
key, value = line.split(':', 1)
91+
mem_info[key.strip()] = value.strip()
92+
93+
return {
94+
"total_memory": mem_info.get('MemTotal', 'Unknown'),
95+
"free_memory": mem_info.get('MemFree', 'Unknown'),
96+
"available_memory": mem_info.get('MemAvailable', 'Unknown')
97+
}
98+
except Exception as e:
99+
return {"error": f"RAM Method 1 failed: {str(e)}"}
100+
101+
def get_ram_info_method2(self):
102+
"""Method 2: Using subprocess and free command"""
103+
try:
104+
if self.system != "linux":
105+
return {"error": "Method 2 only works on Linux systems"}
106+
107+
result = subprocess.run(['free', '-h'], capture_output=True, text=True, timeout=10)
108+
if result.returncode == 0:
109+
lines = result.stdout.split('\n')
110+
if len(lines) >= 2:
111+
headers = lines[0].split()
112+
memory_line = lines[1].split()
113+
return {
114+
"total": memory_line[1] if len(memory_line) > 1 else 'Unknown',
115+
"used": memory_line[2] if len(memory_line) > 2 else 'Unknown',
116+
"free": memory_line[3] if len(memory_line) > 3 else 'Unknown'
117+
}
118+
return {"error": "Failed to parse free command output"}
119+
except Exception as e:
120+
return {"error": f"RAM Method 2 failed: {str(e)}"}
121+
122+
def get_ram_info_method3(self):
123+
"""Method 3: Using psutil if available, otherwise fallback"""
124+
try:
125+
# Try to import psutil
126+
import psutil
127+
memory = psutil.virtual_memory()
128+
return {
129+
"total_gb": round(memory.total / (1024**3), 2),
130+
"available_gb": round(memory.available / (1024**3), 2),
131+
"used_gb": round(memory.used / (1024**3), 2),
132+
"percent_used": memory.percent
133+
}
134+
except ImportError:
135+
return {"error": "psutil not available, using alternative methods"}
136+
except Exception as e:
137+
return {"error": f"RAM Method 3 failed: {str(e)}"}
138+
139+
def collect_all_info(self):
140+
"""Collect all hardware information using multiple methods"""
141+
print("🔍 Collecting Hardware Information...")
142+
print(f"🏷️ System: {platform.system()} {platform.release()}")
143+
print("\n" + "="*50)
144+
145+
# CPU Information
146+
print("\n🖥️ CPU INFORMATION:")
147+
print("-" * 30)
148+
149+
cpu_methods = [
150+
("Platform Module", self.get_cpu_info_method1()),
151+
("/proc/cpuinfo", self.get_cpu_info_method2()),
152+
("System Commands", self.get_cpu_info_method3())
153+
]
154+
155+
for method_name, info in cpu_methods:
156+
print(f"\n📋 {method_name}:")
157+
if "error" in info:
158+
print(f" ❌ {info['error']}")
159+
else:
160+
for key, value in info.items():
161+
print(f" • {key}: {value}")
162+
163+
# RAM Information
164+
print("\n💾 RAM INFORMATION:")
165+
print("-" * 30)
166+
167+
ram_methods = [
168+
("/proc/meminfo", self.get_ram_info_method1()),
169+
("free command", self.get_ram_info_method2()),
170+
("psutil", self.get_ram_info_method3())
171+
]
172+
173+
for method_name, info in ram_methods:
174+
print(f"\n📋 {method_name}:")
175+
if "error" in info:
176+
print(f" ❌ {info['error']}")
177+
else:
178+
for key, value in info.items():
179+
print(f" • {key}: {value}")
180+
181+
return {
182+
"cpu_methods": cpu_methods,
183+
"ram_methods": ram_methods
184+
}
185+
186+
def main():
187+
"""Main function"""
188+
hardware = HardwareInfo()
189+
190+
# Collect all information
191+
all_info = hardware.collect_all_info()
192+
193+
# Save to JSON file for GitHub Actions
194+
output_file = "hardware_info.json"
195+
with open(output_file, 'w') as f:
196+
json.dump(all_info, f, indent=2)
197+
198+
print(f"\n💾 Results saved to: {output_file}")
199+
200+
# Print GitHub Actions format
201+
print("\n🚀 GitHub Actions Output Format:")
202+
print("::set-output name=hardware_info::" + json.dumps({"status": "completed"}))
203+
204+
if __name__ == "__main__":
205+
main()

0 commit comments

Comments
 (0)