-
Notifications
You must be signed in to change notification settings - Fork 65
/
utils.py
106 lines (86 loc) · 2.74 KB
/
utils.py
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
import psutil
from datetime import datetime
import platform
from typing import List
import shutil
import os
def show_time(t):
if isinstance(t, datetime):
return t.strftime('%Y-%m-%d %H:%M:%S')
else:
return datetime.fromtimestamp(t).strftime('%Y-%m-%d %H:%M:%S')
class plat:
name: str = None
chromedriver: str = None
python: str = None
python_path: str = None
driver_path:str =None
if platform.system().lower() == "windows":
plat.name = "windows"
plat.chromedriver = "chromedriver.exe"
plat.python = "python.exe"
elif platform.system().lower() == "linux":
plat.name = "linux"
plat.chromedriver = "chromedriver"
plat.python = "python3"
elif platform.system().lower() == "darwin":
plat.name = "macos"
plat.chromedriver = "chromedriver"
plat.python = "python3"
plat.python_path = shutil.which(plat.python)
plat.driver_path = shutil.which(plat.chromedriver)
if not plat.driver_path:
plat.driver_path = os.path.join(os.path.split(os.path.realpath(__file__))[0], plat.chromedriver)
def kill_process_tree_by_id(pid: int):
try:
parent = psutil.Process(pid)
process: List[psutil.Process] = parent.children(recursive=True)
process.append(parent)
for item in process:
try:
item.kill()
except psutil.NoSuchProcess:
pass
except psutil.NoSuchProcess:
pass
def kill_process_tree_by_name(name: str):
for proc in psutil.process_iter():
if proc.name() == name:
kill_process_tree_by_id(proc.pid)
def all_webdriver() -> List[psutil.Process]:
process = []
for item in psutil.process_iter():
if item.name() == plat.chromedriver:
process.append(item)
return process
def clear_all_webdriver():
process = all_webdriver()
for item in process:
kill_process_tree_by_id(item.pid)
def clear_all_farmer():
for item in psutil.process_iter():
if item.name() == plat.python and "main.py" in item.cmdline():
kill_process_tree_by_id(item.pid)
clear_all_webdriver()
def clear_orphan_webdriver():
process = all_webdriver()
killed = []
for item in process:
if not item.parent():
kill_process_tree_by_id(item.pid)
killed.append(item)
elif item.parent().name().lower() == "systemd":
kill_process_tree_by_id(item.pid)
killed.append(item)
return killed
def test():
proc_list = []
for proc in psutil.process_iter():
if "python.exe" in proc.name():
proc_list.append(proc)
print(proc.name())
print(proc.cmdline())
print(proc.exe())
if __name__ == '__main__':
test()
print(plat.python_path)