-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutilsqh.py
More file actions
executable file
·3413 lines (2870 loc) · 99.6 KB
/
Copy pathutilsqh.py
File metadata and controls
executable file
·3413 lines (2870 loc) · 99.6 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
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
from __future__ import generators
# -*- coding: latin-1 -*-
#$Revision: 522 $, $Date: 2013-11-22 19:06:06 +0100 (vr, 22 nov 2013) $, $Author: quintijn $
#misc utility functions from Quintijn, used in unimacro and in
#local programs.
#copyright Quintijn Hoogenboom, QH software, training & advies
import sys
try:
import checkpath
checkpath.checkpath()
except:
pass
import types, string, os, shutil, copy, filecmp, pywintypes
import glob, re, sys, traceback
import time, filecmp
if sys.platform != 'linux2':
import win32com.client
from win32gui import GetClassName, EnumWindows, GetWindowText, GetWindow
import urllib, difflib
from htmlentitydefs import codepoint2name
import locale
locale.setlocale(locale.LC_ALL, '')
class QHError(Exception):
pass
# for the testing
if sys.platform == 'win32':
testdrive = "C:"
elif sys.platform == 'linux2':
testdrive = "/home/etta"
else:
testdrive = '' # ??
_allchars = string.maketrans('', '')
def translator(frm='', to='', delete='', keep=None):
"""closure function to implement the string.translate functie
python cookbook (2), ch 1 recipe 9
# functions below, see also testUtilsqh.py in unittest.
>>> fixwordquotes('\x91aa\x92')
"'aa'"
>>> fixwordquotes('\x93bb\x94')
'"bb"'
>>> normaliseaccentedchars('d\xe9sir\xe9 //\xddf..# -..e.')
'desireyf-e'
# this one should go before normaliseaccentedchars
#(and after splitting of the extension and folder parts)
>>> fixdotslash('abc/-.def this is no extension.')
'abc_-_def this is no extension_'
## normalise a inivars key (or section)
>>> fixinivarskey('abcd')
'abcd'
>>> fixinivarskey("abcd e'f g")
'abcd ef g'
"""
if len(to) == 1:
to = to * len(frm)
trans = string.maketrans(frm, to)
if keep is not None:
delete = _allchars.translate(_allchars, keep.translate(_allchars, delete))
def translate(s):
return s.translate(trans, delete)
return translate
fixwordquotes = translator('\x91\x92\x93\x94', "''\"\"")
###removenoncharacters = translator('
fixinivarskey = translator(keep=string.letters + ' ')
## function to make translation from e acute to e etc. goes into a translate function with translator
def isaccented(c):
t = chr(c)
try:
name = codepoint2name[c]
except KeyError:
return
if name == t:
return
if len(name) > 1:
return name[0]
# fast translator functions:
accented = [(chr(c), isaccented(c)) for c in range(192,256) if isaccented(c)]
ffrom = ''.join([c for (c,d) in accented])
tto = ''.join([d.lower() for (c,d) in accented])
normaliseaccentedchars = translator(ffrom, tto, keep=ffrom + string.letters + string.digits + "-_")
ffrom = './'
tto = '__'
fixdotslash = translator(ffrom, tto)
ffrom = './ '
tto = '___'
fixdotslashspace = translator(ffrom, tto)
del ffrom
del tto
del accented
del isaccented
del codepoint2name
def curry(func, *args, **kwds):
"""curry from python cookbook, example 15.7,
and python cookbook two: example 16.4.
used for example for class FullTable, which is curried from TableLite
>>> from HTMLgen import TableLite
>>> str(TableLite())
'\\n<table cellspacing="0"></table>'
>>> FullTable = curry(TableLite, border=0, cellpadding=0, cellspacing=0, width = '100%')
>>> str(FullTable())
'\\n<table border="0" cellpadding="0" cellspacing="0" width="100%"></table>'
"""
def curried(*moreargs, **morekwds):
kw = kwds.copy()
kw.update(morekwds)
return func(*(args+moreargs), **kw)
return curried
class peek_ahead(object):
"""Iterator that can look ahead one step
From example 16.7 from python cookbook 2.
The preview can be inspected through it.preview
ignoring duplicates:
>>> it = peek_ahead('122345567')
>>> for i in it:
... if it.preview == i:
... continue
... print i,
1 2 3 4 5 6 7
getting duplicates together:
>>> it = peek_ahead('abbcdddde')
>>> for i in it:
... if it.preview == i:
... dup = 1
... while 1:
... i = it.next()
... dup += 1
... if i != it.preview:
... print i*dup,
... break
... else:
... print i,
...
a bb c dddd e
"""
sentinel = object() #schildwacht
def __init__(self, it):
self._nit = iter(it).next
self.preview = None
self._step()
def __iter__(self):
return self
def next(self):
result = self._step()
if result is self.sentinel: raise StopIteration
else: return result
def _step(self):
result = self.preview
try: self.preview = self._nit()
except StopIteration: self.preview = self.sentinel
return result
class peek_ahead_stripped(peek_ahead):
""" Iterator that strips the lines of text, and returns (leftSpaces,strippedLine)
sentinel is just False, such that peeking ahead can check for truth input
>>> lines = '\\n'.join(['line1', '', ' one space ahead','', ' three spaces ahead, 1 empty line before'])
>>> import StringIO
>>> list(peek_ahead_stripped(StringIO.StringIO(lines)))
[(0, 'line1'), (0, ''), (1, 'one space ahead'), (0, ''), (3, 'three spaces ahead, 1 empty line before')]
example of testing look ahead
>>> lines = '\\n'.join(['line1', '', 'line2 (last)'])
>>> it = peek_ahead_stripped(StringIO.StringIO(lines))
>>> for spaces, text in it:
... print 'current line: |', text, '|',
... if it.preview is it.sentinel:
... print ', cannot preview, end of peek_ahead_stripped'
... elif it.preview[1]:
... print ', non empty preview: |', it.preview[1], '|'
... else:
... print ', empty preview'
current line: | line1 | , empty preview
current line: | | , non empty preview: | line2 (last) |
current line: | line2 (last) | , cannot preview, end of peek_ahead_stripped
"""
sentinel = peek_ahead.sentinel
def next(self):
result = self._step()
if result is self.sentinel: raise StopIteration
else: return result
def _step(self):
"""collect the line and do the processing"""
result = self.preview
try:
line = self._nit().rstrip()
self.preview = (len(line) - len(line.lstrip()), line.lstrip())
except StopIteration: self.preview = self.sentinel
return result
import collections
class peekable(object):
""" An iterator that supports a peek operation.
this is a merge of example 19.18 of python cookbook part 2, peek ahead more steps
and the simpler example 16.7, which peeks ahead one step and stores it in
the self.preview variable.
Adapted so the peek function never raises an error, but gives the
self.sentinel value in order to identify the exhaustion of the iter object.
Example usage:
>>> p = peekable(range(4))
>>> p.peek()
0
>>> p.next(1)
[0]
>>> p.isFirst()
True
>>> p.preview
1
>>> p.isFirst()
True
>>> p.peek(3)
[1, 2, 3]
>>> p.next(2)
[1, 2]
>>> p.peek(2) #doctest: +ELLIPSIS
[3, <object object at ...>]
>>> p.peek(1)
[3]
>>> p.next(2)
Traceback (most recent call last):
StopIteration
>>> p.next()
3
>>> p.isLast()
True
>>> p.next()
Traceback (most recent call last):
StopIteration
>>> p.next(0)
[]
>>> p.peek() #doctest: +ELLIPSIS
<object object at ...>
>>> p.preview #doctest: +ELLIPSIS
<object object at ...>
>>> p.isLast() # after the iter process p.isLast remains True
True
"""
sentinel = object() #schildwacht
def __init__(self, iterable):
self._nit = iter(iterable).next # for speed
self._iterable = iter(iterable)
self._cache = collections.deque()
self._fillcache(1) # initialize the first preview already
self.preview = self._cache[0]
self.count = -1 # keeping the count, possible to check
# isFirst and isLast status
def __iter__(self):
return self
def _fillcache(self, n):
"""fill _cache of items to come, with one extra for the preview variable
"""
if n is None:
n = 1
while len(self._cache) < n+1:
try:
Next = self._nit()
except StopIteration:
# store sentinel, to identify end of iter:
Next = self.sentinel
self._cache.append(Next)
def next(self, n=None):
"""gives next item of the iter, or a list of n items
raises StopIteration if the iter is exhausted (self.sentinel is found),
but in case of n > 1 keeps the iter alive for a smaller "next" calls
"""
self._fillcache(n)
if n is None:
result = self._cache.popleft()
if result == self.sentinel:
# find sentinel, so end of iter:
self.preview = self._cache[0]
raise StopIteration
self.count += 1
else:
result = [self._cache.popleft() for i in range(n)]
if result and result[-1] == self.sentinel:
# recache for future use:
self._cache.clear()
self._cache.extend(result)
self.preview = self._cache[0]
raise StopIteration
self.count += n
self.preview = self._cache[0]
return result
def isFirst(self):
"""returns true if iter is at first position
"""
return self.count == 0
def isLast(self):
"""returns true if iter is at last position or after StopIteration
"""
return self.preview == self.sentinel
def peek(self, n=None):
"""gives next item, without exhausting the iter, or a list of 0 or more next items
with n == None, you can also use the self.preview variable, which is the first item
to come.
"""
self._fillcache(n)
if n is None:
result = self._cache[0]
else:
result = [self._cache[i] for i in range(n)]
return result
def get_best_match(texts, match_against, ignore=' ', treshold=0.9):
"""Get the best matching from texts, none if treshold is not reached
texts: list of texts to choose from
match_against: text wanted
ignore: junk characters (set eg to "_ ")
treshold: best match must be at least this value.
"""
# JUNK = space _
# now time to figre out the matching
ratio_calc = difflib.SequenceMatcher(lambda x: x in ignore)
ratio_calc.set_seq1(match_against)
ratios = {}
best_ratio = 0
best_text = ''
for text in texts:
# set up the SequenceMatcher with other text
ratio_calc.set_seq2(text)
# calculate ratio and store it
ratios[text] = ratio_calc.ratio()
# if this is the best so far then update best stats
if ratios[text] > best_ratio:
best_ratio = ratios[text]
best_text = text
if best_ratio > treshold:
return best_text
def isSubList(largerList, smallerList):
"""returns 1 if smallerList is a sub list of largerList
>>> isSubList([1,2,4,3,2,3], [2,3])
1
>>> isSubList([1,2,3,2,2,2,2], [2])
1
>>> isSubList([1,2,3,2], [2,4])
"""
if not smallerList:
raise ValueError("isSubList: smallerList is empty: %s"% smallerList)
item0 = smallerList[0]
lenSmaller = len(smallerList)
lenLarger = len(largerList)
if lenSmaller > lenLarger:
return # can not be sublist
# get possible relevant indexes for first item
indexes0 = [i for (i,item) in enumerate(largerList) if item == item0 and i <= lenLarger-lenSmaller]
if not indexes0:
return
for start in indexes0:
slice = largerList[start:start+lenSmaller]
if slice == smallerList:
return 1
def ifelse(var, ifyes, ifno):
"""ternary operator simulated, if var: True else: False
idea from "learning python"
>>> x = []
>>> print ifelse(x, 'a', 'b')
b
>>> y = 'yes'
>>> print ifelse(y, 12, 23)
12
"""
if var:
return ifyes
else:
return ifno
def isSubList(largerList, smallerList):
"""returns 1 if smallerList is a sub list of largerList
for use in voicecode...
>>> isSubList([1,2,4,3,2,3], [2,3])
1
>>> isSubList([1,2,3,2,2,2,2], [2])
1
>>> isSubList([1,2,3,2], [2,4])
"""
if not smallerList:
raise ValueError("isSubList: smallerList is empty: %s"% smallerList)
item0 = smallerList[0]
lenSmaller = len(smallerList)
lenLarger = len(largerList)
if lenSmaller > lenLarger:
return # can not be sublist
# get possible relevant indexes for first item
indexes0 = [i for (i,item) in enumerate(largerList) if item == item0 and i <= lenLarger-lenSmaller]
if not indexes0:
return
for start in indexes0:
slice = largerList[start:start+lenSmaller]
if slice == smallerList:
return 1
# helper string functions:
def replaceExt(fileName, ext):
"""change extension of file
>>> replaceExt("a.psd", ".jpg")
'a.jpg'
>>> replaceExt("a/b/c/d.psd", "jpg")
\'a/b/c/d.jpg'
"""
ext = addToStart(ext, ".")
fileName = str(fileName)
a, extOld = os.path.splitext(fileName)
return a + ext
def getExt(fileName):
"""return the extension of a file
>>> getExt("a.psd")
'.psd'
>>> getExt("a/b/c/d.psd")
'.psd'
>>> getExt("abcd")
''
>>> getExt("a/b/xyz")
''
"""
a, ext = os.path.splitext(fileName)
return ext
def removeFromStart(text, toRemove, ignoreCase=None):
"""returns the text with "toRemove" stripped from the start if it matches
>>> removeFromStart('abcd', 'a')
'bcd'
>>> removeFromStart('abcd', 'not')
'abcd'
working of ignoreCase:
>>> removeFromStart('ABCD', 'a')
'ABCD'
>>> removeFromStart('ABCD', 'ab', ignoreCase=1)
'CD'
>>> removeFromStart('abcd', 'ABC', ignoreCase=1)
'd'
"""
if ignoreCase:
text2 = text.lower()
toRemove = toRemove.lower()
else:
text2 = text
if text2.startswith(toRemove):
return text[len(toRemove):]
else:
return text
def removeFromEnd(text, toRemove, ignoreCase=None):
"""returns the text with "toRemove" stripped from the end if it matches
>>> removeFromEnd('a.jpg', '.jpg')
'a'
>>> removeFromEnd('b.jpg', '.gif')
'b.jpg'
working of ignoreCase:
>>> removeFromEnd('C.JPG', '.jpg')
'C.JPG'
>>> removeFromEnd('D.JPG', '.jpg', ignoreCase=1)
'D'
>>> removeFromEnd('d.jpg', '.JPG', ignoreCase=1)
'd'
"""
if ignoreCase:
text2 = text.lower()
toRemove = toRemove.lower()
else:
text2 = text
if text2.endswith(toRemove):
return text[:-len(toRemove)]
else:
return text
def addToStart(text, toAdd, ignoreCase=None):
"""returns text with "toAdd" added at the start if it was not already there
if ignoreCase:
return the start of the string with the case as in "toAdd"
>>> addToStart('a-text', 'a-')
'a-text'
>>> addToStart('text', 'b-')
'b-text'
>>> addToStart('B-text', 'b-')
'b-B-text'
working of ignoreCase:
>>> addToStart('C-Text', 'c-', ignoreCase=1)
'c-Text'
>>> addToStart('d-Text', 'D-', ignoreCase=1)
'D-Text'
"""
if ignoreCase:
text2 = text.lower()
toAdd2 = toAdd.lower()
else:
text2 = text
toAdd2 = toAdd
if text2.startswith(toAdd2):
return toAdd + text[len(toAdd):]
else:
return toAdd + text
def addToEnd(text, toAdd, ignoreCase=None):
"""returns text with "toAdd" added at the end if it was not already there
if ignoreCase:
return the end of the string with the case as in "toAdd"
>>> addToEnd('a.jpg', '.jpg')
'a.jpg'
>>> addToEnd('b', '.jpg')
'b.jpg'
working of ignoreCase:
>>> addToEnd('Cd.JPG', '.jpg', ignoreCase=1)
'Cd.jpg'
>>> addToEnd('Ef.jpg', '.JPG', ignoreCase=1)
'Ef.JPG'
"""
if ignoreCase:
text2 = text.lower()
toAdd2 = toAdd.lower()
else:
text2 = text
toAdd2 = toAdd
if text2.endswith(toAdd2):
return text[:-len(toAdd)] + toAdd
else:
return text + toAdd
def firstLetterCapitalize(t):
"""capitalize only the first letter of the string
"""
if t:
return t[0].upper() + t[1:]
else:
return ""
def extToLower(fileName):
"""leave name part intact, but change extension to lowercase
>>> extToLower("aBc.jpg")
'aBc.jpg'
>>> extToLower("ABC.JPG")
'ABC.jpg'
>>> extToLower("D:/a/B/ABC.JPG")
'D:/a/B/ABC.jpg'
"""
f, ext = os.path.splitext(fileName)
return f + ext.lower()
def appendBeforeExt(text, toAppend):
"""append text just before the extension of the filename part
>>> appendBeforeExt("short.html", '__t')
'short__t.html'
>>> appendBeforeExt("http://a/b/c/d/long.html", '__b')
'http://a/b/c/d/long__b.html'
"""
base, ext = os.path.splitext(text)
return base + toAppend + ext
def getBaseFolder(globalsDict):
"""get in a module the folder of this module.
either sys.argv[0] (when run direct) or
__file__, which can be empty. In that case take the working directory
"""
baseFolder = ""
if globalsDict['__name__'] == "__main__":
baseFolder = os.path.split(sys.argv[0])[0]
print 'baseFolder from argv: %s'% baseFolder
elif globalsDict['__file__']:
baseFolder = os.path.split(globalsDict['__file__'])[0]
print 'baseFolder from __file__: %s'% baseFolder
if not baseFolder:
baseFolder = os.getcwd()
print 'baseFolder was empty, take wd: %s'% baseFolder
return baseFolder
Classes = ('ExploreWClass', 'CabinetWClass')
def partition_range(max_range):
"""partition for milla website in lengths of 3 or 4
>>> partition_range(3)
[[0], [1], [2]]
>>> partition_range(5)
[[0], [1], [2], [3, 4]]
>>> partition_range(8)
[[0, 1], [2, 3], [4, 5], [6, 7]]
>>> partition_range(12)
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]]
"""
lst = range(max_range)
if max_range <= 4:
return [[i] for i in lst]
elif max_range == 5:
L = [[i] for i in range(4)]
L[3].append(4)
return L
elif max_range == 6:
return [[0, 1], [2, 3], [4, 5]]
elif max_range == 7:
return [[0], [1, 2], [3, 4], [5, 6]]
elif max_range == 8:
return [[0, 1], [2, 3], [4, 5], [6, 7]]
else:
return [lst] # alle images achter elkaar, scrollen afhankelijk van de browser
def unravelList(menu):
"""unravel from menu list to dropdown list order
>>> unravelList([1, [2, [3, 4, 5], 6], 7, 8])
[[1, 7, 8], [2, 6], [3, 4, 5]]
"""
L, M = [], None
for elt in menu:
if type(elt) == types.ListType:
M = unravelList(elt)
else:
L.append(elt)
if M and type(M) == types.ListType:
M.insert(0, L)
return M
else:
return [L]
reUnix=re.compile(r'[^\w-]')
def toUnixName(t, glueChar="", lowercase=1, canHaveExtension=1, canHaveFolders=1):
"""get rid of unwanted characters, only letters and '-'
leading numbers get a _ in front
default: all to lowercase, if lowercase = 0: convert extension to lowercase anyway
default: file can have extension and folders. If set to 0, also \\, / and . are removed from name.
split into folder/file parts if needed.
glueChar can be "_" or "-" as well ("_" for avp, michel)
>>> toUnixName('')
Traceback (most recent call last):
ValueError: toUnixName, name has no valid characters: ||
>>> toUnixName('-abcd')
'_-abcd'
>>> toUnixName('aDc')
'adc'
>>> toUnixName('a.b-99? .d')
'a_b-99.d'
>>> toUnixName('a.b-99? .d', canHaveExtension=0)
'a_b-99_d'
>>> toUnixName('.a^.jpg')
'_a.jpg'
>>> toUnixName('6-barge.txt')
'_6-barge.txt'
>>> toUnixName('-6-barge.html')
'_-6-barge.html'
>>> toUnixName('D:/abc.def/-6-barge.html')
'D:/abc_def/_-6-barge.html'
>>> toUnixName('D:/abc.def/Thaddeus M'+chr(252)+'ller.html')
'D:/abc_def/thaddeusmuller.html'
>>>
"""
t = os.path.normpath(t)
t = t.replace('\\', '/')
if canHaveFolders and t.find('/') >= 0:
L = []
parts = t.split('/')
for part in parts:
if part != parts[ - 1]:
canHaveExtension2 = 0 # folder parts never extension
else:
canHaveExtension2 = canHaveExtension
if lowercase and not (len(part) == 2 \
and part[-1] == ":"):
part = part.lower()
sofar = path('/'.join(L))/part
if sofar.isdir():
# prevent "website name" from being converted
L.append(part)
continue
L.append(toUnixName(part,lowercase=lowercase, canHaveFolders=0,
canHaveExtension=canHaveExtension2))
return '/'.join(L)
if len(t) == 2 and t.endswith(":"):
return t.upper()
if t == "..":
return t
# now for the dir/file part:
if canHaveExtension:
trunk, ext = os.path.splitext(t)
else:
# also remove . and / (and \)
trunk, ext = t, ''
if glueChar == "_":
trunk = fixdotslashspace(trunk) # . --> _ and / -->> _ also space to "_"
elif glueChar:
raise ValueError('toUnixName, glueChar may only be "" or "_", not "%s"'% glueChar)
else:
trunk = fixdotslash(trunk) # . --> _ and / -->> _
trunk = normaliseaccentedchars(trunk)
if lowercase:
trunk = trunk.lower()
# remove possible invalid chars from extension:
if ext and ext[0] == ".":
ext = "." + normaliseaccentedchars(ext[1:])
ext = ext.lower() # always to lowercase
if not trunk:
raise ValueError("toUnixName, name has no valid characters: |%s|"% trunk)
if trunk[0] in '-0123456789':
trunk = "_" + trunk
return trunk + ext
str2unix = toUnixName
def sendkeys_escape(str):
"""escape with {} keys that have a special meaning in sendkeys
+ ^ % ~ { } [ ]
>>> sendkeys_escape('abcd')
'abcd'
>>> sendkeys_escape('+bcd')
'{+}bcd'
>>> sendkeys_escape('+a^b%c~d{f}g[h]i')
'{+}a{^}b{%}c{~}d{{}f{}}g{[}h{]}i'
>>> sendkeys_escape('+^%~{}[]')
'{+}{^}{%}{~}{{}{}}{[}{]}'
"""
return ''.join(map(_sendkeys_escape, str))
def _sendkeys_escape(s):
"""Escape one character in the set or return if different"""
if s in ('+', '^', '%', '~', '{' , '}' , '[' , ']' ) :
return '{%s}' % s
else:
return s
##import sys, traceback
def print_exc_plus(filename=None, skiptypes=None, takemodules=None,
specials=None):
""" Print the usual traceback information, followed by a listing of
all the local variables in each frame.
"""
#print 'specials:', specials
# normal traceback:
traceback.print_exc()
tb = sys.exc_info()[2]
while tb.tb_next:
tb = tb.tb_next
stack = []
f = tb.tb_frame
while f:
stack.append(f)
f = f.f_back
stack.reverse()
traceback.print_exc()
L = []
# keys that are in specialsSitegen are recorded in next array:
specialsDict = {}
push = L.append
push('traceback date/time: %s'% time.asctime(time.localtime(time.time())))
pagename = ''
menuname = ''
for frame in stack:
if takemodules and not filter(None, [frame.f_code.co_filename.find(t) > 0 for t in takemodules]):
continue
functionname = frame.f_code.co_name
push('\nFrame "%s" in %s at line %s' % (frame.f_code.co_name,
frame.f_code.co_filename,
frame.f_lineno))
keys = []
values = []
for key, value in frame.f_locals.items():
if key[0:2] == '__':
continue
try:
v = repr(value)
except:
continue
if skiptypes and filter(None, [v.find(s) == 1 for s in skiptypes]):
continue
keys.append(key)
if functionname == 'go' and key == 'self':
if v.find('Menu instance') > 0:
menuname = value.name
push('menu name: %s'% menuname)
if functionname == 'makePage' and key == 'self':
if v.find('Page instance') > 0:
pagename = value.name
push('page name: %s'% pagename)
# we must _absolutely_ avoid propagating exceptions, and str(value)
# COULD cause any exception, so we MUST catch any...:
v = v.replace('\n', '|')
values.append(v)
if keys:
maxlenkeys = max(15, max(map(len, keys)))
allowedlength = 80-maxlenkeys
kv = zip(keys, values)
kv.sort()
for k,v in kv:
if v.startswith('<built-in method'):
continue
if len(v) > allowedlength:
half = allowedlength/2
v = v[:half] + " ... " + v[-half:]
push(k.rjust(maxlenkeys) + " = " + v)
if specials:
stack.reverse()
for frame in stack:
if 'self' in frame.f_locals:
push('\ncontents of self (%s)'% repr(frame.f_locals['self']))
inst = frame.f_locals['self']
keys, values = [], []
for key in dir(inst):
value = getattr(inst, key)
if key[0:2] == '__':
continue
try:
v = repr(value)
except:
continue
if skiptypes and filter(None, [v.find(s) == 1 for s in skiptypes]):
continue
# specials for eg sitegen
if specials and key in specials:
#print 'found specialskey: %s: %s'% (key, v)
specialsDict[key] = v
keys.append(key)
# we must _absolutely_ avoid propagating exceptions, and str(value)
# COULD cause any exception, so we MUST catch any...:
v = v.replace('\n', '|')
values.append(v)
if not keys:
break
maxlenkeys = max(15, max(map(len, keys)))
allowedlength = 80-maxlenkeys
for k,v in zip(keys, values):
if len(v) > allowedlength:
half = allowedlength/2
v = v[:half] + " ... " + v[-half:]
push(k.rjust(maxlenkeys) + " = " + v)
break
else:
print 'no self of HTMLDoc found'
callback = []
if menuname:
push('menu: %s'% menuname)
callback.append('menu: %s'% menuname)
elif pagename == 'index':
push('menu: top')
callback.append('menu: top')
if pagename:
push('page: %s'% pagename)
callback.append('page: %s'% pagename)
push('\ntype: %s, value: %s'% (sys.exc_info()[0], sys.exc_info()[1]))
callback.append('error: %s'%sys.exc_info()[1])
print '\nerror occurred:'
callback = '\n'.join(callback)
print callback
sys.stderr.write('\n'.join(L))
sys.stderr.write(callback)
#print 'result specialsDict: %s'% specialsDict
return callback, specialsDict
def cleanTraceback(tb, filesToSkip=None):
"""strip boilerplate in traceback (unittest)
the purpose is to skip the lines "Traceback" (only if filesToSkip == True),
and to skip traceback lines from modules that are in filesToSkip.
in use with unimacro unittest and voicecode unittesting.
filesToSkip are (can be "unittest.py" and "TestCaseWithHelpers.py"
"""
L = tb.split('\n')
snip = " ..." # leaving a sign of the stripping!
if filesToSkip:
singleLineSkipping = ["Traceback (most recent call last):"]
else:
singleLineSkipping = None
M = []
skipNext = 0
for line in L:
# skip the traceback line:
if singleLineSkipping and line in singleLineSkipping:
continue
# skip trace lines from one one the filesToSkip and the next one
# UNLESS there are no leading spaces, in case we hit on the error line itself.
if skipNext and line.startswith(" "):
skipNext = 0
continue
if filesToSkip:
for f in filesToSkip:
if line.find(f + '", line') >= 0:
skipNext = 1
if M and M[-1] == snip:
pass