-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess_manager.py
More file actions
130 lines (108 loc) · 4.24 KB
/
process_manager.py
File metadata and controls
130 lines (108 loc) · 4.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
import psutil
def list_processes():
"""
Listează toate procesele active: PID, nume, user, memorie (%).
"""
print("\n=== Lista proceselor active ===")
print(f"{'PID':>6} {'USER':<15} {'NAME':<30} {'MEM%':>6}")
print("-" * 65)
for proc in psutil.process_iter(['pid', 'name', 'username', 'memory_percent']):
try:
info = proc.info
pid = info.get("pid")
name = info.get("name") or "?"
user = info.get("username") or "?"
mem = info.get("memory_percent") or 0.0
print(f"{pid:>6} {user:<15.15} {name:<30.30} {mem:6.2f}")
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
continue
def search_processes(query: str):
"""
Caută procese după nume (case-insensitive).
"""
print(f"\n=== Căutare procese care conțin: '{query}' ===")
found = False
for proc in psutil.process_iter(['pid', 'name', 'username', 'memory_percent']):
try:
info = proc.info
name = info.get("name") or ""
if query.lower() in name.lower():
found = True
pid = info.get("pid")
user = info.get("username") or "?"
mem = info.get("memory_percent") or 0.0
print(f"PID={pid} USER={user} NAME={name} MEM={mem:.2f}%")
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
continue
if not found:
print("⚠️ Niciun proces găsit cu acest nume.")
def show_top_memory(n: int = 5):
"""
Arată top N procese care consumă cea mai multă memorie.
"""
processes = []
for proc in psutil.process_iter(['pid', 'name', 'username', 'memory_percent']):
try:
info = proc.info
processes.append(info)
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
continue
# sortăm descrescător după memorie
processes.sort(key=lambda p: p.get("memory_percent") or 0.0, reverse=True)
print(f"\n=== Top {n} procese după memorie ===")
print(f"{'PID':>6} {'USER':<15} {'NAME':<30} {'MEM%':>6}")
print("-" * 65)
for info in processes[:n]:
pid = info.get("pid")
name = info.get("name") or "?"
user = info.get("username") or "?"
mem = info.get("memory_percent") or 0.0
print(f"{pid:>6} {user:<15.15} {name:<30.30} {mem:6.2f}")
def kill_process(pid: int):
"""
Încearcă să termine (terminate) un proces după PID.
"""
try:
proc = psutil.Process(pid)
name = proc.name()
proc.terminate()
proc.wait(timeout=3)
print(f"✅ Procesul cu PID={pid} ({name}) a fost terminat.")
except psutil.NoSuchProcess:
print("❌ Procesul nu există.")
except psutil.AccessDenied:
print("❌ Acces refuzat. Încearcă să rulezi cu privilegii mai mari (sudo).")
except psutil.TimeoutExpired:
print("⚠️ Procesul nu a răspuns la terminate(). Poți încerca kill (proc.kill()).")
except Exception as e:
print(f"❌ Eroare neașteptată: {e}")
def main_menu():
while True:
print("\n=== Process Manager CLI ===")
print("1. Listează toate procesele")
print("2. Caută proces după nume")
print("3. Arată top 5 procese după memorie")
print("4. Termină un proces după PID")
print("5. Ieșire")
choice = input("Alege o opțiune (1-5): ").strip()
if choice == "1":
list_processes()
elif choice == "2":
query = input("Introdu numele (sau parte din nume) procesului: ").strip()
if query:
search_processes(query)
elif choice == "3":
show_top_memory(5)
elif choice == "4":
pid_input = input("Introdu PID-ul procesului de terminat: ").strip()
if pid_input.isdigit():
kill_process(int(pid_input))
else:
print("⚠️ PID invalid.")
elif choice == "5":
print("👋 Ieșire din Process Manager CLI.")
break
else:
print("⚠️ Opțiune invalidă. Încearcă din nou.")
if __name__ == "__main__":
main_menu()