-
Notifications
You must be signed in to change notification settings - Fork 3
/
util.py
192 lines (155 loc) · 4.86 KB
/
util.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
"""
util module
"""
from time import strftime, localtime
from typing import List, Any
import enum
import os
import shutil
import subprocess
def show_step(step):
"""
shows step
"""
if True:
print(step)
def check_file_directory_exists(address: str, to_quit: bool):
"""
checks if specified directory exists. if not, exits.
:param address: address of file or directory to be checked.
:param to_quit: determines if to exit if address does not exist.
"""
if os.path.exists(address):
return True
else:
print(address + " does not exist")
if not to_quit:
return False
else:
quit()
return False
def move_dir_safe(source: str, destination: str):
'''
moves directory from `source` to `destination`
'''
if os.path.isdir(source) and os.path.isdir(destination):
print('checked. Moving ', source, destination)
remove_existing_file_directory(destination)
shutil.move(source, destination)
else:
print('something wrong with safe_move: ')
print(source, destination)
def StringToBoolean(value: str):
if value == "True":
return True
elif value == "False":
return False
else:
raise ValueError("value must be True/False. You provided: "+value)
def remove_existing_file_directory(address: str):
"""
checks if the file/directory exists is provided address.
if exists, removes. if not, nothing!
:param address: address of file or directory
"""
if check_file_directory_exists(address, False):
try:
shutil.rmtree(address)
except NotADirectoryError:
os.remove(address)
def kill_process_using_pid(pid: str):
'''
kills a process using specified `pid`
'''
if pid:
try:
subprocess.check_output(['kill', '-9', pid])
print('killed process using pid: ' + pid)
except subprocess.CalledProcessError:
print('error. most possibly there is no pid by ' + pid)
def detail_print(variable):
'''
pretty prints the `variable`. If it is a `List`, it prints accordingly.
'''
import pprint
if isinstance(variable, List):
for i in variable:
try:
pprint.pprint(i.__dict__)
except AttributeError:
if isinstance(i, str):
print(i)
else:
pprint.pprint(variable.__dict__)
def list_as_enum_name_list(integer_list: List[int], enum_type) -> List[str]:
'''
replaces values based on names of enums
'''
if not integer_list:
raise ValueError("List must not be empty")
if not isinstance(enum_type, enum.EnumMeta):
raise ValueError("enum_type must be enum")
enum_name_list = []
for i in integer_list:
enum_name_list.append(enum_type(i).name)
return enum_name_list
def return_current_time():
'''
returns current time in YYYYMMDDHHmm format.
'''
return strftime("%Y%m%d%H%M", localtime())
def return_current_time_in_logcat_style():
'''
return current time in logcat threadtime style
"%m-%d %H::%M::%S"
'''
return strftime("%m-%d %H:%M:%S", localtime())
def debug_print(*msg: Any, flag: bool):
'''
prints if the provided flag is true
'''
if flag:
print(msg)
def pid_from_emulator_port(emulator_port: str) -> int:
'''
:param emulator_port:
integer `emulator_port`
returns:
PID of provided `emulator_port`
'''
tcp_port = "tcp:" + str(emulator_port)
# lsof -sTcp:LISTEN -iTcp:5555
pid = subprocess.check_output(
['lsof', '-sTcp:LISTEN', '-i', tcp_port])
pid = pid.decode()
# COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
# qemu-syst 11803 amit 52u IPv4 1855210 0t0 TCP localhost:5555
# (LISTEN)
pid = pid.split('\n')[1:][0].split(' ')[1]
# 11803
return int(pid)
def ps_details_of_pid(pid: int) -> str:
'''
retuns:
device details from `pid`
'''
device_details = subprocess.check_output(['ps', str(pid)])
device_details = device_details.decode().strip()
return device_details
def change_file_permission(filename_with_full_path: str, permission: int):
'''
`permission` in 3 digit number
'''
check_file_directory_exists(filename_with_full_path, True)
subprocess.check_output(
['chmod', str(permission), filename_with_full_path])
def print_dual_list(list_one: List, list_two: List):
'''
prints two same length lists matching each other in the following format.
eg:
>>> "{}: {}".format(list_one[i], list_two[i])
'''
if not len(list_one) == len(list_two):
raise ValueError("List length mismatched")
for i in range(0, len(list_one) - 1):
print("{}: {}".format(list_one[i], list_two[i]))