-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathascmini.py
1778 lines (1621 loc) · 57 KB
/
ascmini.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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim: set ts=4 sw=4 tw=0 et :
#======================================================================
#
# ascmini.py - mini library
#
# Created by skywind on 2017/03/24
# Version: 8, Last Modified: 2022/10/18 23:22
#
#======================================================================
from __future__ import print_function, unicode_literals
import sys
import time
import os
import socket
import collections
import json
#----------------------------------------------------------------------
# python 2/3 compatible
#----------------------------------------------------------------------
if sys.version_info[0] >= 3:
long = int
unicode = str
xrange = range
UNIX = (sys.platform[:3] != 'win') and True or False
#----------------------------------------------------------------------
# call program and returns output (combination of stdout and stderr)
#----------------------------------------------------------------------
def execute(args, shell = False, capture = False):
import sys, os
parameters = []
cmd = None
if not isinstance(args, list):
import shlex
cmd = args
if sys.platform[:3] == 'win':
ucs = False
if sys.version_info[0] < 3:
if not isinstance(cmd, str):
cmd = cmd.encode('utf-8')
ucs = True
args = shlex.split(cmd.replace('\\', '\x00'))
args = [ n.replace('\x00', '\\') for n in args ]
if ucs:
args = [ n.decode('utf-8') for n in args ]
else:
args = shlex.split(cmd)
for n in args:
if sys.platform[:3] != 'win':
replace = { ' ':'\\ ', '\\':'\\\\', '\"':'\\\"', '\t':'\\t',
'\n':'\\n', '\r':'\\r' }
text = ''.join([ replace.get(ch, ch) for ch in n ])
parameters.append(text)
else:
if (' ' in n) or ('\t' in n) or ('"' in n):
parameters.append('"%s"'%(n.replace('"', ' ')))
else:
parameters.append(n)
if cmd is None:
cmd = ' '.join(parameters)
if sys.platform[:3] == 'win' and len(cmd) > 255:
shell = False
if shell and (not capture):
os.system(cmd)
return b''
elif (not shell) and (not capture):
import subprocess
if 'call' in subprocess.__dict__:
subprocess.call(args)
return b''
import subprocess
if 'Popen' in subprocess.__dict__:
p = subprocess.Popen(args, shell = shell,
stdin = subprocess.PIPE, stdout = subprocess.PIPE,
stderr = subprocess.STDOUT)
stdin, stdouterr = (p.stdin, p.stdout)
else:
p = None
stdin, stdouterr = os.popen4(cmd)
stdin.close()
text = stdouterr.read()
stdouterr.close()
if p: p.wait()
if not capture:
sys.stdout.write(text)
sys.stdout.flush()
return b''
return text
#----------------------------------------------------------------------
# call subprocess and returns retcode, stdout, stderr
#----------------------------------------------------------------------
def call(args, input_data = None, combine = False):
import sys, os
parameters = []
for n in args:
if sys.platform[:3] != 'win':
replace = { ' ':'\\ ', '\\':'\\\\', '\"':'\\\"', '\t':'\\t',
'\n':'\\n', '\r':'\\r' }
text = ''.join([ replace.get(ch, ch) for ch in n ])
parameters.append(text)
else:
if (' ' in n) or ('\t' in n) or ('"' in n):
parameters.append('"%s"'%(n.replace('"', ' ')))
else:
parameters.append(n)
cmd = ' '.join(parameters)
import subprocess
bufsize = 0x100000
if input_data is not None:
if not isinstance(input_data, bytes):
if sys.stdin and sys.stdin.encoding:
input_data = input_data.encode(sys.stdin.encoding, 'ignore')
elif sys.stdout and sys.stdout.encoding:
input_data = input_data.encode(sys.stdout.encoding, 'ignore')
else:
input_data = input_data.encode('utf-8', 'ignore')
size = len(input_data) * 2 + 0x10000
if size > bufsize:
bufsize = size
if 'Popen' in subprocess.__dict__:
p = subprocess.Popen(args, shell = False, bufsize = bufsize,
stdin = subprocess.PIPE, stdout = subprocess.PIPE,
stderr = combine and subprocess.STDOUT or subprocess.PIPE)
stdin, stdout, stderr = p.stdin, p.stdout, p.stderr
if combine: stderr = None
else:
p = None
if combine is False:
stdin, stdout, stderr = os.popen3(cmd)
else:
stdin, stdout = os.popen4(cmd)
stderr = None
if input_data is not None:
stdin.write(input_data)
stdin.flush()
stdin.close()
exeout = stdout.read()
if stderr: exeerr = stderr.read()
else: exeerr = None
stdout.close()
if stderr: stderr.close()
retcode = None
if p:
retcode = p.wait()
return retcode, exeout, exeerr
#----------------------------------------------------------------------
# redirect process output to reader(what, text)
#----------------------------------------------------------------------
def redirect(args, reader, combine = True):
import subprocess
parameters = []
for n in args:
if sys.platform[:3] != 'win':
replace = { ' ':'\\ ', '\\':'\\\\', '\"':'\\\"', '\t':'\\t',
'\n':'\\n', '\r':'\\r' }
text = ''.join([ replace.get(ch, ch) for ch in n ])
parameters.append(text)
else:
if (' ' in n) or ('\t' in n) or ('"' in n):
parameters.append('"%s"'%(n.replace('"', ' ')))
else:
parameters.append(n)
cmd = ' '.join(parameters)
if 'Popen' in subprocess.__dict__:
p = subprocess.Popen(args, shell = False,
stdin = subprocess.PIPE, stdout = subprocess.PIPE,
stderr = combine and subprocess.STDOUT or subprocess.PIPE)
stdin, stdout, stderr = p.stdin, p.stdout, p.stderr
if combine: stderr = None
else:
p = None
if combine is False:
stdin, stdout, stderr = os.popen3(cmd)
else:
stdin, stdout = os.popen4(cmd)
stderr = None
stdin.close()
while 1:
text = stdout.readline()
if text in (b'', ''):
break
reader('stdout', text)
while stderr is not None:
text = stderr.readline()
if text in (b'', ''):
break
reader('stderr', text)
stdout.close()
if stderr: stderr.close()
retcode = None
if p:
retcode = p.wait()
return retcode
#----------------------------------------------------------------------
# OBJECT:enchanced object
#----------------------------------------------------------------------
class OBJECT (object):
def __init__ (self, **argv):
for x in argv: self.__dict__[x] = argv[x]
def __getitem__ (self, x):
return self.__dict__[x]
def __setitem__ (self, x, y):
self.__dict__[x] = y
def __delitem__ (self, x):
del self.__dict__[x]
def __contains__ (self, x):
return self.__dict__.__contains__(x)
def __len__ (self):
return self.__dict__.__len__()
def __repr__ (self):
line = [ '%s=%s'%(k, repr(v)) for k, v in self.__dict__.items() ]
return 'OBJECT(' + ', '.join(line) + ')'
def __str__ (self):
return self.__repr__()
def __iter__ (self):
return self.__dict__.__iter__()
#----------------------------------------------------------------------
# call stack
#----------------------------------------------------------------------
def callstack ():
import traceback
if sys.version_info[0] < 3:
import cStringIO
sio = cStringIO.StringIO()
else:
import io
sio = io.StringIO()
traceback.print_exc(file = sio)
return sio.getvalue()
#----------------------------------------------------------------------
# Posix tools
#----------------------------------------------------------------------
class PosixKit (object):
def __init__ (self):
self.unix = (sys.platform[:3] != 'win')
# get short path name on windows
def pathshort (self, path):
if path is None:
return None
path = os.path.abspath(path)
if sys.platform[:3] != 'win':
return path
kernel32 = None
textdata = None
GetShortPathName = None
try:
import ctypes
kernel32 = ctypes.windll.LoadLibrary("kernel32.dll")
textdata = ctypes.create_string_buffer(b'\000' * 1034)
GetShortPathName = kernel32.GetShortPathNameA
args = [ ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int ]
GetShortPathName.argtypes = args
GetShortPathName.restype = ctypes.c_uint32
except:
pass
if not GetShortPathName:
return path
if not isinstance(path, bytes):
path = path.encode(sys.stdout.encoding, 'ignore')
retval = GetShortPathName(path, textdata, 1034)
shortpath = textdata.value
if retval <= 0:
return ''
if isinstance(path, bytes):
if sys.stdout.encoding:
shortpath = shortpath.decode(sys.stdout.encoding, 'ignore')
return shortpath
def mkdir (self, path):
unix = sys.platform[:3] != 'win' and True or False
path = os.path.abspath(path)
if os.path.exists(path):
return False
name = ''
part = os.path.abspath(path).replace('\\', '/').split('/')
if unix:
name = '/'
if (not unix) and (path[1:2] == ':'):
part[0] += '/'
for n in part:
name = os.path.abspath(os.path.join(name, n))
if not os.path.exists(name):
os.mkdir(name)
return True
# remove tree
def rmtree (self, path, ignore_error = False, onerror = None):
import shutil
shutil.rmtree(path, ignore_error, onerror)
return True
# absolute path
def abspath (self, path, resolve = False):
if path is None:
return None
if '~' in path:
path = os.path.expanduser(path)
path = os.path.abspath(path)
if not UNIX:
return path.lower().replace('\\', '/')
if resolve:
return os.path.abspath(os.path.realpath(path))
return path
# find files
def find (self, path, extnames = None):
result = []
if extnames:
if UNIX == 0:
extnames = [ n.lower() for n in extnames ]
extnames = tuple(extnames)
for root, _, files in os.walk(path):
for name in files:
if extnames:
ext = os.path.splitext(name)[-1]
if UNIX == 0:
ext = ext.lower()
if ext not in extnames:
continue
result.append(os.path.abspath(os.path.join(root, name)))
return result
# which file
def which (self, name, prefix = None, postfix = None):
if not prefix:
prefix = []
if not postfix:
postfix = []
PATH = os.environ.get('PATH', '').split(UNIX and ':' or ';')
search = prefix + PATH + postfix
for path in search:
fullname = os.path.join(path, name)
if os.path.exists(fullname):
return fullname
return None
# search executable
def search_exe (self, exename, prefix = None, postfix = None):
path = self.which(exename, prefix, postfix)
if path is None:
return None
return self.pathshort(path)
# executable
def search_cmd (self, cmdname, prefix = None, postfix = None):
if sys.platform[:3] == 'win':
ext = os.path.splitext(cmdname)[-1].lower()
if ext:
return self.search_exe(cmdname, prefix, postfix)
for ext in ('.cmd', '.bat', '.exe', '.vbs'):
path = self.which(cmdname + ext, prefix, postfix)
if path:
return self.pathshort(path)
return self.search_exe(cmdname)
# load content
def load_file_content (self, filename, mode = 'r'):
if hasattr(filename, 'read'):
try: content = filename.read()
except: pass
return content
try:
fp = open(filename, mode)
content = fp.read()
fp.close()
except:
content = None
return content
# save file content
def save_file_content (self, filename, content, mode = 'w'):
try:
fp = open(filename, mode)
fp.write(content)
fp.close()
except:
return False
return True
# find file recursive
def find_files (self, cwd, pattern = '*.*'):
import fnmatch
matches = []
for root, dirnames, filenames in os.walk(cwd):
for filename in fnmatch.filter(filenames, pattern):
matches.append(os.path.join(root, filename))
return matches
# load file and guess encoding
def load_file_text (self, filename, encoding = None):
content = self.load_file_content(filename, 'rb')
if content is None:
return None
if content[:3] == b'\xef\xbb\xbf':
text = content[3:].decode('utf-8')
elif encoding is not None:
text = content.decode(encoding, 'ignore')
else:
text = None
guess = [sys.getdefaultencoding(), 'utf-8']
if sys.stdout and sys.stdout.encoding:
guess.append(sys.stdout.encoding)
try:
import locale
guess.append(locale.getpreferredencoding())
except:
pass
visit = {}
for name in guess + ['gbk', 'ascii', 'latin1']:
if name in visit:
continue
visit[name] = 1
try:
text = content.decode(name)
break
except:
pass
if text is None:
text = content.decode('utf-8', 'ignore')
return text
# save file text
def save_file_text (self, filename, content, encoding = None):
import codecs
if encoding is None:
encoding = 'utf-8'
if (not isinstance(content, unicode)) and isinstance(content, bytes):
return self.save_file_content(filename, content)
with codecs.open(filename, 'w',
encoding = encoding,
errors = 'ignore') as fp:
fp.write(content)
return True
# load ini without ConfigParser
def load_ini (self, filename, encoding = None):
text = self.load_file_text(filename, encoding)
config = {}
sect = 'default'
if text is None:
return None
for line in text.split('\n'):
line = line.strip('\r\n\t ')
if not line:
continue
elif line[:1] in ('#', ';'):
continue
elif line.startswith('['):
if line.endswith(']'):
sect = line[1:-1].strip('\r\n\t ')
if sect not in config:
config[sect] = {}
else:
pos = line.find('=')
if pos >= 0:
key = line[:pos].rstrip('\r\n\t ')
val = line[pos + 1:].lstrip('\r\n\t ')
if sect not in config:
config[sect] = {}
config[sect][key] = val
return config
#----------------------------------------------------------------------
# instance
#----------------------------------------------------------------------
posix = PosixKit()
#----------------------------------------------------------------------
# file content load/save
#----------------------------------------------------------------------
def load_config(path):
import json
try:
text = posix.load_file_content(path, 'rb')
if text is None:
return None
if sys.version_info[0] < 3:
if text[:3] == '\xef\xbb\xbf': # remove BOM+
text = text[3:]
return json.loads(text, encoding = "utf-8")
else:
if text[:3] == b'\xef\xbb\xbf': # remove BOM+
text = text[3:]
text = text.decode('utf-8', 'ignore')
return json.loads(text)
except:
return None
return None
def save_config(path, obj):
import json
if sys.version_info[0] < 3:
text = json.dumps(obj, indent = 4, encoding = "utf-8") + '\n'
else:
text = json.dumps(obj, indent = 4) + '\n'
text = text.encode('utf-8', 'ignore')
if not posix.save_file_content(path, text, 'wb'):
return False
return True
#----------------------------------------------------------------------
# http_request
#----------------------------------------------------------------------
def http_request(url, timeout = 10, data = None, post = False, head = None):
headers = []
import urllib
import ssl
status = -1
if sys.version_info[0] >= 3:
import urllib.parse
import urllib.request
import urllib.error
if data is not None:
if isinstance(data, dict):
data = urllib.parse.urlencode(data)
if not post:
if data is None:
req = urllib.request.Request(url)
else:
mark = '?' in url and '&' or '?'
req = urllib.request.Request(url + mark + data)
else:
data = data is not None and data or ''
if not isinstance(data, bytes):
data = data.encode('utf-8', 'ignore')
req = urllib.request.Request(url, data)
if head:
for k, v in head.items():
req.add_header(k, v)
try:
res = urllib.request.urlopen(req, timeout = timeout)
headers = res.getheaders()
except urllib.error.HTTPError as e:
return e.code, str(e.message), None
except urllib.error.URLError as e:
return -1, str(e), None
except socket.timeout:
return -2, 'timeout', None
except ssl.SSLError:
return -2, 'timeout', None
content = res.read()
status = res.getcode()
else:
import urllib2
if data is not None:
if isinstance(data, dict):
part = {}
for key in data:
val = data[key]
if isinstance(key, unicode):
key = key.encode('utf-8')
if isinstance(val, unicode):
val = val.encode('utf-8')
part[key] = val
data = urllib.urlencode(part)
if not isinstance(data, bytes):
data = data.encode('utf-8', 'ignore')
if not post:
if data is None:
req = urllib2.Request(url)
else:
mark = '?' in url and '&' or '?'
req = urllib2.Request(url + mark + data)
else:
req = urllib2.Request(url, data is not None and data or '')
if head:
for k, v in head.items():
req.add_header(k, v)
try:
res = urllib2.urlopen(req, timeout = timeout)
content = res.read()
status = res.getcode()
if res.info().headers:
for line in res.info().headers:
line = line.rstrip('\r\n\t')
pos = line.find(':')
if pos < 0:
continue
key = line[:pos].rstrip('\t ')
val = line[pos + 1:].lstrip('\t ')
headers.append((key, val))
except urllib2.HTTPError as e:
return e.code, str(e.message), None
except urllib2.URLError as e:
return -1, str(e), None
except socket.timeout:
return -2, 'timeout', None
except ssl.SSLError:
return -2, 'timeout', None
return status, content, headers
#----------------------------------------------------------------------
# request with retry
#----------------------------------------------------------------------
def request_safe(url, timeout = 10, retry = 3, verbose = True, delay = 1):
for i in xrange(retry):
if verbose:
print('%s: %s'%(i == 0 and 'request' or 'retry', url))
time.sleep(delay)
code, content, _ = http_request(url, timeout)
if code == 200:
return content
return None
#----------------------------------------------------------------------
# request json rpc
#----------------------------------------------------------------------
def json_rpc_post(url, message, timeout = 10):
import json
data = json.dumps(message)
header = [('Content-Type', 'text/plain; charset=utf-8')]
code, content, _ = http_request(url, timeout, data, True, header)
if code == 200:
content = json.loads(content)
return code, content
#----------------------------------------------------------------------
# timestamp
#----------------------------------------------------------------------
def timestamp(ts = None, onlyday = False):
import time
if not ts: ts = time.time()
if onlyday:
time.strftime('%Y%m%d', time.localtime(ts))
return time.strftime('%Y%m%d%H%M%S', time.localtime(ts))
#----------------------------------------------------------------------
# timestamp
#----------------------------------------------------------------------
def readts(ts, onlyday = False):
if onlyday: ts += '000000'
try: return time.mktime(time.strptime(ts, '%Y%m%d%H%M%S'))
except: pass
return 0
#----------------------------------------------------------------------
# parse text
#----------------------------------------------------------------------
def parse_conf_text(text, default = None):
if text is None:
return default
if isinstance(default, str):
return text
elif isinstance(default, bool):
text = text.lower()
if not text:
return default
text = text.lower()
if default:
if text in ('false', 'f', 'no', 'n', '0'):
return False
else:
if text in ('true', 'ok', 'yes', 't', 'y', '1'):
return True
if text.isdigit():
try:
value = int(text)
if value:
return True
except:
pass
return default
elif isinstance(default, float):
try:
value = float(text)
return value
except:
return default
elif isinstance(default, int) or isinstance(default, long):
multiply = 1
text = text.strip('\r\n\t ')
postfix1 = text[-1:].lower()
postfix2 = text[-2:].lower()
if postfix1 == 'k':
multiply = 1024
text = text[:-1]
elif postfix1 == 'm':
multiply = 1024 * 1024
text = text[:-1]
elif postfix2 == 'kb':
multiply = 1024
text = text[:-2]
elif postfix2 == 'mb':
multiply = 1024 * 1024
text = text[:-2]
try: text = int(text.strip('\r\n\t '), 0)
except: text = default
if multiply > 1:
text *= multiply
return text
return text
#----------------------------------------------------------------------
# ConfigReader
#----------------------------------------------------------------------
class ConfigReader (object):
def __init__ (self, ininame, codec = None):
self.ininame = ininame
self.reset()
self.load(ininame, codec)
def reset (self):
self.config = {}
self.sections = []
return True
def load (self, ininame, codec = None):
if not ininame:
return False
elif not os.path.exists(ininame):
return False
try:
content = open(ininame, 'rb').read()
except IOError:
content = b''
if content[:3] == b'\xef\xbb\xbf':
text = content[3:].decode('utf-8')
elif codec is not None:
text = content.decode(codec, 'ignore')
else:
codec = sys.getdefaultencoding()
text = None
for name in [codec, 'gbk', 'utf-8']:
try:
text = content.decode(name)
break
except:
pass
if text is None:
text = content.decode('utf-8', 'ignore')
if sys.version_info[0] < 3:
import StringIO
import ConfigParser
sio = StringIO.StringIO(text)
cp = ConfigParser.ConfigParser()
cp.readfp(sio)
else:
import configparser
cp = configparser.ConfigParser(interpolation = None)
cp.read_string(text)
for sect in cp.sections():
for key, val in cp.items(sect):
lowsect, lowkey = sect.lower(), key.lower()
self.config.setdefault(lowsect, {})[lowkey] = val
if 'default' not in self.config:
self.config['default'] = {}
return True
def option (self, section, item, default = None):
sect = self.config.get(section, None)
if not sect:
return default
text = sect.get(item, None)
if text is None:
return default
return parse_conf_text(text, default)
#----------------------------------------------------------------------
# Csv Read/Write
#----------------------------------------------------------------------
def csv_load (filename, encoding = None):
content = None
text = None
try:
content = open(filename, 'rb').read()
except:
return None
if content is None:
return None
if content[:3] == b'\xef\xbb\xbf':
text = content[3:].decode('utf-8')
elif encoding is not None:
text = content.decode(encoding, 'ignore')
else:
codec = sys.getdefaultencoding()
text = None
for name in [codec, 'utf-8', 'gbk', 'ascii', 'latin1']:
try:
text = content.decode(name)
break
except:
pass
if text is None:
text = content.decode('utf-8', 'ignore')
if not text:
return None
import csv
if sys.version_info[0] < 3:
import cStringIO
sio = cStringIO.StringIO(text.encode('utf-8', 'ignore'))
else:
import io
sio = io.StringIO(text)
reader = csv.reader(sio)
output = []
if sys.version_info[0] < 3:
for row in reader:
output.append([ n.decode('utf-8', 'ignore') for n in row ])
else:
for row in reader:
output.append(row)
return output
def csv_save (filename, rows, encoding = 'utf-8'):
import csv
ispy2 = (sys.version_info[0] < 3)
if not encoding:
encoding = 'utf-8'
if sys.version_info[0] < 3:
fp = open(filename, 'wb')
writer = csv.writer(fp)
else:
fp = open(filename, 'w', encoding = encoding, newline = '')
writer = csv.writer(fp)
for row in rows:
newrow = []
for n in row:
if isinstance(n, int) or isinstance(n, long):
n = str(n)
elif isinstance(n, float):
n = str(n)
elif not isinstance(n, bytes):
if (n is not None) and ispy2:
n = n.encode(encoding, 'ignore')
newrow.append(n)
writer.writerow(newrow)
fp.close()
return True
#----------------------------------------------------------------------
# object pool
#----------------------------------------------------------------------
class ObjectPool (object):
def __init__ (self):
import threading
self._pools = {}
self._lock = threading.Lock()
def get (self, name):
hr = None
self._lock.acquire()
pset = self._pools.get(name, None)
if pset:
hr = pset.pop()
self._lock.release()
return hr
def put (self, name, obj):
self._lock.acquire()
pset = self._pools.get(name, None)
if pset is None:
pset = set()
self._pools[name] = pset
pset.add(obj)
self._lock.release()
return True
#----------------------------------------------------------------------
# WebKit
#----------------------------------------------------------------------
class WebKit (object):
def __init__ (self):
pass
# Check IS FastCGI
def IsFastCGI (self):
import socket, errno
if 'fromfd' not in socket.__dict__:
return False
try:
s = socket.fromfd(sys.stdin.fileno(), socket.AF_INET,
socket.SOCK_STREAM)
s.getpeername()
except socket.error as err:
if err.errno != errno.ENOTCONN:
return False
return True
def text2html (self, s):
import cgi
return cgi.escape(s, True).replace('\n', "</br>\n")
def html2text (self, html):
part = []
pos = 0
while 1:
f1 = html.find('<', pos)
if f1 < 0:
part.append((0, html[pos:]))
break
f2 = html.find('>', f1)
if f2 < 0:
part.append((0, html[pos:]))
break
text = html[pos:f1]
flag = html[f1:f2 + 1]
pos = f2 + 1
if text:
part.append((0, text))
if flag:
part.append((1, flag))
output = ''
for mode, text in part:
if mode == 0:
text = text.lstrip()
text = text.replace(' ', ' ').replace('>', '>')
text = text.replace('<', '<').replace('&', '&')
output += text
else:
text = text.strip()
tiny = text.replace(' ', '')
if tiny in ('</p>', '<p/>', '<br>', '</br>', '<br/>'):
output += '\n'
elif tiny in ('</tr>', '<tr/>', '</h1>', '</h2>', '</h3>'):
output += '\n'
elif tiny in ('</td>', '<td/>'):
output += ' '
elif tiny in ('</div>',):
output += '\n'
return output
def match_text (self, text, position, starts, ends):
p1 = text.find(starts, position)
if p1 < 0:
return None, position
p2 = text.find(ends, p1 + len(starts))
if p2 < 0:
return None, position
value = text[p1 + len(starts):p2]
return value, p2 + len(ends)
def replace_range (self, text, start, size, newtext):
head = text[:start]
tail = text[start + size:]
return head + newtext + tail
def url_parse (self, url):
if sys.version_info[0] < 3:
import urlparse
return urlparse.urlparse(url)
import urllib.parse
return urllib.parse.urlparse(url)
def url_unquote (self, text, plus = True):
if sys.version_info[0] < 3:
import urllib
if plus:
return urllib.unquote_plus(text)
return urllib.unquote(text)
import urllib.parse
if plus:
return urllib.parse.unquote_plus(text)
return urllib.parse.unquote(text)
def url_quote (self, text, plus = True):
if sys.version_info[0] < 3:
import urllib
if plus:
return urllib.quote_plus(text)
return urlparse.quote(text)
import urllib.parse
if plus:
return urllib.parse.quote_plus(text)