/
debug.py
390 lines (357 loc) · 16.8 KB
/
debug.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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
#-*- encoding: utf-8 -*-
#encoding: utf-8
VERSION = "X.X"
import colorama
import termcolor
import inspect
import random
import socket
import cmdw
import os
import sys
import datetime
from make_colors import make_colors
import colorama
import configparser
import re
import traceback
PID = os.getpid()
try:
colorama.init(True)
except:
pass
MAX_WIDTH = cmdw.getWidth()
DEBUG = False
if DEBUG == 1 or DEBUG == '1':
DEBUG = True
elif DEBUG == 0 or DEBUG == '0':
DEBUG = False
if os.getenv('DEBUG') == 1 or os.getenv('DEBUG') == '1':
DEBUG = True
if os.getenv('DEBUG') == 0 or os.getenv('DEBUG') == '0':
DEBUG = False
if isinstance(DEBUG, str):
DEBUG = bool(DEBUG.title())
DEBUG_SERVER = os.getenv('DEBUG_SERVER')
if DEBUG_SERVER == 1 or DEBUG_SERVER == '1':
DEBUG_SERVER = True
if DEBUG_SERVER == 0 or DEBUG_SERVER == '0':
DEBUG_SERVER = False
if DEBUG_SERVER == "True" or DEBUG_SERVER == True:
DEBUG_SERVER = True
DEBUGGER_SERVER = ['127.0.0.1:50001']
CONFIG_NAME = os.path.join(os.path.dirname(__file__), 'debug.ini')
try:
cfg = configparser.RawConfigParser(allow_no_value=True)
cfg.read(CONFIG_NAME)
cfg = cfg.get('DEBUGGER', 'HOST')
if ";" in cfg:
DEBUGGER_SERVER = re.split(";", cfg)
else:
DEBUGGER_SERVER = [cfg]
except:
traceback.format_exc()
if os.getenv('DEBUGGER_SERVER'):
if ";" in os.getenv('DEBUGGER_SERVER'):
DEBUGGER_SERVER = os.getenv('DEBUGGER_SERVER').strip().split(";")
else:
DEBUGGER_SERVER = [os.getenv('DEBUGGER_SERVER')]
FILENAME = ''
if os.getenv('DEBUG_FILENAME'):
FILENAME = os.getenv('DEBUG_FILENAME')
#def excepthook(type, value, tb):
#traceback.format_exc(etype = type, value = value, tb = tb)
#try:
#sys.excepthook = excepthook
#except:
#traceback.format_exc()
class debugger(object):
global VERSION
global CONFIG_NAME
VERSION = "x.x"
def __init__(self, defname = None, debug = None, filename = None, **kwargs):
super(debugger, self)
self.DEBUG = debug
self.FILENAME = filename
if DEBUG:
self.DEBUG = DEBUG
if FILENAME:
self.FILENAME = FILENAME
#print "self.FILENAME =", self.FILENAME
if os.getenv('DEBUG') and os.getenv('DEBUG') == 1 or os.getenv('DEBUG') and os.getenv('DEBUG') == '1' or os.getenv('DEBUG') and os.getenv('DEBUG') == True or os.getenv('DEBUG') and os.getenv('DEBUG') == "True":
self.DEBUG = True
self.color_random_error = False
def version(cls):
print "version:", VERSION
version = classmethod(version)
def get_config_file(self, filename='', verbosity=None):
global CONFIG_NAME
if filename == '':
if CONFIG_NAME != '':
filename = CONFIG_NAME
# else:
# return WindowsError('No Config file found !')
if os.path.isfile(os.path.join(os.getcwd(), filename)):
#print "FILENAME ZZZ=", f
CONFIG_NAME = os.path.join(os.getcwd(), filename)
if verbosity:
print os.path.join(os.getcwd(), filename)
return os.path.join(os.getcwd(), filename)
elif os.path.isfile(filename):
CONFIG_NAME = filename
if verbosity:
print os.path.abspath(CONFIG_NAME)
return filename
elif os.path.isfile(os.path.join(os.path.dirname(__file__), filename)):
CONFIG_NAME = os.path.join(os.path.dirname(__file__), filename)
if verbosity:
print os.path.join(os.path.dirname(__file__), filename)
return os.path.join(os.path.dirname(__file__), filename)
elif os.path.isfile(CONFIG_NAME):
if verbosity:
print os.path.abspath(CONFIG_NAME)
return CONFIG_NAME
elif os.path.isfile(os.path.join(os.path.dirname(__file__), CONFIG_NAME)):
if verbosity:
print os.path.join(os.path.dirname(__file__), CONFIG_NAME)
return os.path.join(os.path.dirname(__file__), CONFIG_NAME)
else:
fcfg = os.path.join(os.path.dirname(__file__), CONFIG_NAME)
f = open(fcfg, 'w')
f.close()
filecfg = fcfg
if verbosity:
print "CREATE:", os.path.abspath(filecfg)
return filecfg
def read_config(self, section, option, filename='', verbosity=None): #format result: [aaa.bbb.ccc.ddd, eee.fff.ggg.hhh, qqq.xxx.yyy.zzz]
"""
option: section, option, filename=''
format result: [aaa.bbb.ccc.ddd, eee.fff.ggg.hhh, qqq.xxx.yyy.zzz]
"""
filename = get_config_file(filename, verbosity)
data = []
cfg = configparser.RawConfigParser(allow_no_value=True, dict_type=MultiOrderedDict)
cfg.read(filename)
cfg = cfg.get(section, option)
if not cfg == None:
for i in cfg:
if "," in i:
d1 = str(i).split(",")
for j in d1:
data.append(str(j).strip())
else:
data.append(i)
return data
else:
return None
def debug_server_client(self, msg, server_host = '127.0.0.1', port = 50001):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
if DEBUGGER_SERVER:
for i in DEBUGGER_SERVER:
if ":" in i:
host, port = str(i).strip().split(":")
port = int(port.strip())
host = host.strip()
else:
host = i.strip()
s.sendto(msg, (host, port))
s.close()
else:
print "self.read_config('DEBUGGER', 'HOST') =", self.read_config('DEBUGGER', 'HOST')
if self.read_config('DEBUGGER', 'HOST'):
if ":" in self.read_config('DEBUGGER', 'HOST'):
host, port = str(self.read_config('DEBUGGER', 'HOST')).strip().split(":")
port = int(port.strip())
host = host.strip()
else:
host = self.read_config('DEBUGGER', 'HOST').strip()
s.sendto(msg, (host, port))
s.close()
def setDebug(self, debug):
self.DEBUG = debug
def printlist(self, defname = None, debug = None, filename = '', linenumbers = '', print_function_parameters = False, **kwargs):
if DEBUG_SERVER:
debug_server = True
if not filename:
filename = self.FILENAME
frame = inspect.currentframe()
args, _, _, values = inspect.getargvalues(frame)
if not debug:
debug = self.DEBUG
if sys.platform == 'win32':
try:
color_random_1 = [colorama.Fore.GREEN, colorama.Fore.YELLOW, colorama.Fore.LIGHTWHITE_EX, colorama.Fore.LIGHTCYAN_EX, colorama.Fore.LIGHTMAGENTA_EX, colorama.Fore.GREEN, colorama.Fore.YELLOW, colorama.Fore.LIGHTWHITE_EX, colorama.Fore.LIGHTCYAN_EX, colorama.Fore.LIGHTMAGENTA_EX, colorama.Fore.GREEN, colorama.Fore.YELLOW, colorama.Fore.LIGHTWHITE_EX, colorama.Fore.LIGHTCYAN_EX, colorama.Fore.LIGHTMAGENTA_EX, colorama.Fore.GREEN, colorama.Fore.YELLOW, colorama.Fore.LIGHTWHITE_EX, colorama.Fore.LIGHTCYAN_EX, colorama.Fore.LIGHTMAGENTA_EX, colorama.Fore.GREEN, colorama.Fore.YELLOW, colorama.Fore.LIGHTWHITE_EX, colorama.Fore.LIGHTCYAN_EX, colorama.Fore.LIGHTMAGENTA_EX, colorama.Fore.GREEN, colorama.Fore.YELLOW, colorama.Fore.LIGHTWHITE_EX, colorama.Fore.LIGHTCYAN_EX, colorama.Fore.LIGHTMAGENTA_EX]
self.color_random_error = False
except:
self.color_random_error = True
pass
else:
color_random_1 = [colorama.Fore.GREEN, colorama.Fore.YELLOW, colorama.Fore.WHITE, colorama.Fore.CYAN, colorama.Fore.MAGENTA, colorama.Fore.GREEN, colorama.Fore.YELLOW, colorama.Fore.WHITE, colorama.Fore.CYAN, colorama.Fore.MAGENTA, colorama.Fore.GREEN, colorama.Fore.YELLOW, colorama.Fore.WHITE, colorama.Fore.CYAN, colorama.Fore.MAGENTA, colorama.Fore.GREEN, colorama.Fore.YELLOW, colorama.Fore.WHITE, colorama.Fore.CYAN, colorama.Fore.MAGENTA, colorama.Fore.GREEN, colorama.Fore.YELLOW, colorama.Fore.WHITE, colorama.Fore.CYAN, colorama.Fore.MAGENTA, colorama.Fore.GREEN, colorama.Fore.YELLOW, colorama.Fore.WHITE, colorama.Fore.CYAN, colorama.Fore.MAGENTA]
try:
colorama.init()
except:
pass
formatlist = ''
try:
arrow = colorama.Fore.YELLOW + ' -> '
except:
arrow = ' -> '
if print_function_parameters:
for i in args:
if i == 'self':
pass
else:
try:
formatlist = termcolor.colored((str(i) + ": "), 'white', 'on_blue') + color_random_1[int(args.index(i))] + str(values[i]) + arrow
except:
formatlist = str(i) + ": " + str(values[i]) + arrow
if not defname:
defname = str(inspect.stack()[1][3])
if filename == None:
filename = sys.argv[0]
linenumbers = str(inspect.stack()[1][2])
try:
formatlist = termcolor.colored(datetime.datetime.strftime(datetime.datetime.now(), '%Y:%m:%d~%H:%M:%S:%f'), 'white') + " " + termcolor.colored(defname + arrow, 'white', 'on_red') + formatlist + " " + "[" + str(filename) + "]" + " [" + termcolor.colored(str(linenumbers), 'white', 'on_cyan') + "] "
except:
formatlist = datetime.datetime.strftime(datetime.datetime.now(), '%Y:%m:%d~%H:%M:%S:%f') + " " + defname + arrow + formatlist + " " + "[" + str(filename) + "]" + " [" + str(linenumbers) + "] "
if debug:
print formatlist
if DEBUG_SERVER:
self.debug_server_client(formatlist)
return formatlist
if not kwargs == {}:
for i in kwargs:
#formatlist += color_random_1[kwargs.keys().index(i)] + i + ": " + color_random_1[kwargs.keys().index(i)] + str(kwargs.get(i)) + arrow
try:
if str(kwargs.get(str(i))) == '':
formatlist += termcolor.colored((str(i)), 'white', 'on_blue') + arrow
else:
formatlist += termcolor.colored((str(i) + ": "), 'white', 'on_blue') + color_random_1[kwargs.keys().index(i)] + str(kwargs.get(str(i))) + arrow
except:
try:
print termcolor.colored("DEBUGGER ERROR !", 'white', 'on_red', attrs= ['bold', 'blink'])
except:
pass
#traceback.format_exc()
try:
if str(kwargs.get(str(i))) == '':
formatlist += str(i) + arrow
else:
formatlist += str(i) + ": " + str(kwargs.get(str(i))) + arrow
except:
traceback.format_exc()
else:
try:
formatlist += random.choice(color_random_1) + " start... " + arrow
except:
try:
formatlist += " start... " + arrow
except:
formatlist += " start... " + ' -> '
formatlist = formatlist[:-4]
if defname:
if filename == None:
#frame = inspect.stack()[1]
#module = inspect.getmodule(frame[0])
#filename = module.__file__
#filename = inspect.stack()[2][3]
filename = sys.argv[0]
#defname = defname + " [" + str(inspect.stack()[0][2]) + "] "
try:
formatlist = termcolor.colored(datetime.datetime.strftime(datetime.datetime.now(), '%Y:%m:%d~%H:%M:%S:%f'), 'white') + " " + termcolor.colored(defname + arrow, 'white', 'on_red') + formatlist + " " + "[" + str(filename) + "]" + " " + termcolor.colored("[", "cyan") + termcolor.colored(str(linenumbers)[2:-2], 'white', 'on_cyan') + termcolor.colored("]", "cyan")
except:
formatlist = datetime.datetime.strftime(datetime.datetime.now(), '%Y:%m:%d~%H:%M:%S:%f') + " " + defname + arrow + formatlist + " " + "[" + str(filename) + "]" + " " + "[" + str(linenumbers)[2:-2] + "]"
else:
defname = str(inspect.stack()[1][3])
try:
line_number = " [" + termcolor.colored(str(inspect.stack()[1][2]), 'white', 'on_cyan') + "] "
except:
line_number = " [" + str(inspect.stack()[1][2]) + "] "
if filename == None:
filename = sys.argv[0]
#filename = inspect.stack()[2][3]
#frame = inspect.stack()[1]
#module = inspect.getmodule(frame[0])
#filename = module.__file__
#f = sys._current_frames().values()[0]
#filename = f.f_back.f_globals['__file__']
try:
formatlist = termcolor.colored(datetime.datetime.strftime(datetime.datetime.now(), '%Y:%m:%d~%H:%M:%S:%f'), 'white') + " " + termcolor.colored(defname + arrow, 'white', 'on_red') + formatlist + " " + "[" + str(filename) + " [" + termcolor.colored(str(inspect.stack()[1][2]), 'white', 'on_cyan') + "] " + line_number
except:
formatlist = datetime.datetime.strftime(datetime.datetime.now(), '%Y:%m:%d~%H:%M:%S:%f') + " " + defname + arrow + formatlist + " " + "[" + str(filename) + " [" + str(inspect.stack()[1][2]) + "] " + line_number
if debug:
try:
print formatlist
colorama.reinit()
except:
pass
if DEBUG_SERVER:
self.debug_server_client(formatlist + " [%s]" % (PID))
#if debug_server:
#self.debug_server_client(formatlist)
return formatlist
def debug_server_client(msg, server_host = '127.0.0.1', port = 50001):
global CONFIG_NAME
try:
if read_config('RECEIVER', 'HOST', CONFIG_NAME):
RECEIVER_HOST = read_config('RECEIVER', 'HOST', CONFIG_NAME)
except:
pass
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
if RECEIVER_HOST:
for i in RECEIVER_HOST:
if ":" in i:
host, port = str(i).strip().split(":")
port = int(port.strip())
host = host.strip()
else:
host = i.strip()
s.sendto(msg, (host, port))
s.close()
def serve(host = '0.0.0.0', port = 50001):
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
print make_colors("BIND: ", 'white', 'green') + make_colors(host, 'white', 'red', attrs= ['bold']) + ":" + make_colors(str(port), 'white', 'yellow', attrs= ['bold'])
while 1:
msg = s.recv(65565)
if msg:
print msg
print "=" * (MAX_WIDTH - 3)
def debug(defname = None, debug = None, debug_server = False, line_number = '', print_function_parameters = False, **kwargs):
isdebug = DEBUG
#if DEBUG_SERVER:
#debug_server = True
if not defname:
#print "inspect.stack =", inspect.stack()[1][2]
defname = inspect.stack()[1][3]
line_number = " [" + termcolor.colored(str(inspect.stack()[1][2]), 'white', 'on_cyan') + "] "
#defname = str(inspect.stack()[1][3]) + " [" + str(inspect.stack()[1][2]) + "] "
c = debugger(defname, debug)
msg = c.printlist(defname, debug, linenumbers = line_number, print_function_parameters= print_function_parameters, **kwargs)
#if DEBUG_SERVER:
#debug_server_client(msg)
#if debug_server:
#debug_server_client(msg)
def usage():
import argparse
parser = argparse.ArgumentParser(description= 'run debugger as server receive debug text default port is 50001', version= "1.0", formatter_class= argparse.RawTextHelpFormatter)
parser.add_argument('-b', '--host', action = 'store', help = 'Bind / listen ip address, default all network device: 0.0.0.0', default = '0.0.0.0', type = str)
parser.add_argument('-p', '--port', action = 'store', help = 'Bind / listen port number, default is 50001', default = 50001, type = int)
if len(sys.argv) == 1:
print "\n"
parser.print_help()
try:
args = parser.parse_args()
serve(args.host, args.port)
except KeyboardInterrupt:
sys.exit()
else:
try:
args = parser.parse_args()
serve(args.host, args.port)
except KeyboardInterrupt:
sys.exit()
if __name__ == '__main__':
print "PID:", PID
usage()