public
Description: wxWidgets Python bindings
Homepage: http://code.google.com/p/wxpy
Clone URL: git://github.com/kevinwatters/wxpy.git
Search Repo:
wxpy / path.py
100644 985 lines (786 sloc) 32.536 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
""" path.py - An object representing a path to a file or directory.
 
Example:
 
from path import path
d = path('/home/guido/bin')
for f in d.files('*.py'):
f.chmod(0755)
 
This module requires Python 2.2 or later.
 
 
URL: http://www.jorendorff.com/articles/python/path
Author: Jason Orendorff <jason.orendorff\x40gmail\x2ecom> (and others - see the url!)
Date: 9 Mar 2007
"""
 
 
# TODO
# - Tree-walking functions don't avoid symlink loops. Matt Harrison
# sent me a patch for this.
# - Bug in write_text(). It doesn't support Universal newline mode.
# - Better error message in listdir() when self isn't a
# directory. (On Windows, the error message really sucks.)
# - Make sure everything has a good docstring.
# - Add methods for regex find and replace.
# - guess_content_type() method?
# - Perhaps support arguments to touch().
 
from __future__ import generators
 
import sys, warnings, os, fnmatch, glob, shutil, codecs, md5, subprocess
 
__version__ = '2.2'
__all__ = ['path']
 
# Platform-specific support for path.owner
if os.name == 'nt':
    try:
        import win32security
    except ImportError:
        win32security = None
else:
    try:
        import pwd
    except ImportError:
        pwd = None
 
# Pre-2.3 support. Are unicode filenames supported?
_base = str
_getcwd = os.getcwd
try:
    if os.path.supports_unicode_filenames:
        _base = unicode
        _getcwd = os.getcwdu
        _filesystem_encoding = sys.getfilesystemencoding()
except AttributeError:
    pass
 
# Pre-2.3 workaround for booleans
try:
    True, False
except NameError:
    True, False = 1, 0
 
# Pre-2.3 workaround for basestring.
try:
    basestring
except NameError:
    basestring = (str, unicode)
 
# Universal newline support
_textmode = 'r'
if hasattr(file, 'newlines'):
    _textmode = 'U'
 
 
class TreeWalkWarning(Warning):
    pass
 
class path(_base):
    """ Represents a filesystem path.
 
For documentation on individual methods, consult their
counterparts in os.path.
"""
 
    # --- Special Python methods.
 
    def __repr__(self):
        return 'path(%s)' % _base.__repr__(self)
 
    # Adding a path and a string yields a path.
    def __add__(self, more):
        try:
            resultStr = _base.__add__(self, more)
        except TypeError: #Python bug
            resultStr = NotImplemented
        if resultStr is NotImplemented:
            return resultStr
        return self.__class__(resultStr)
 
    def __radd__(self, other):
        if isinstance(other, basestring):
            return self.__class__(other.__add__(self))
        else:
            return NotImplemented
 
    # The / operator joins paths.
    def __div__(self, rel):
        """ fp.__div__(rel) == fp / rel == fp.joinpath(rel)
 
Join two path components, adding a separator character if
needed.
"""
        return self.__class__(os.path.join(self, rel))
 
    # Make the / operator work even when true division is enabled.
    __truediv__ = __div__
 
    def getcwd(cls):
        """ Return the current working directory as a path object. """
        return cls(_getcwd())
    getcwd = classmethod(getcwd)
 
 
    # --- Operations on path strings.
 
    isabs = os.path.isabs
    def abspath(self): return self.__class__(os.path.abspath(self))
    def normcase(self): return self.__class__(os.path.normcase(self))
    def normpath(self): return self.__class__(os.path.normpath(self))
    def realpath(self): return self.__class__(os.path.realpath(self))
    def expanduser(self): return self.__class__(os.path.expanduser(self))
    def expandvars(self): return self.__class__(os.path.expandvars(self))
    def dirname(self): return self.__class__(os.path.dirname(self))
    basename = os.path.basename
 
    def expand(self):
        """ Clean up a filename by calling expandvars(),
expanduser(), and normpath() on it.
 
This is commonly everything needed to clean up a filename
read from a configuration file, for example.
"""
        return self.expandvars().expanduser().normpath()
 
    def _get_namebase(self):
        base, ext = os.path.splitext(self.name)
        return base
 
    def _get_ext(self):
        f, ext = os.path.splitext(_base(self))
        return ext
 
    def _get_drive(self):
        drive, r = os.path.splitdrive(self)
        return self.__class__(drive)
 
    parent = property(
        dirname, None, None,
        """ This path's parent directory, as a new path object.
 
For example, path('/usr/local/lib/libpython.so').parent == path('/usr/local/lib')
""")
 
    name = property(
        basename, None, None,
        """ The name of this file or directory without the full path.
 
For example, path('/usr/local/lib/libpython.so').name == 'libpython.so'
""")
 
    namebase = property(
        _get_namebase, None, None,
        """ The same as path.name, but with one file extension stripped off.
 
For example, path('/home/guido/python.tar.gz').name == 'python.tar.gz',
but path('/home/guido/python.tar.gz').namebase == 'python.tar'
""")
 
    ext = property(
        _get_ext, None, None,
        """ The file extension, for example '.py'. """)
 
    drive = property(
        _get_drive, None, None,
        """ The drive specifier, for example 'C:'.
This is always empty on systems that don't use drive specifiers.
""")
 
    def splitpath(self):
        """ p.splitpath() -> Return (p.parent, p.name). """
        parent, child = os.path.split(self)
        return self.__class__(parent), child
 
    def splitdrive(self):
        """ p.splitdrive() -> Return (p.drive, <the rest of p>).
 
Split the drive specifier from this path. If there is
no drive specifier, p.drive is empty, so the return value
is simply (path(''), p). This is always the case on Unix.
"""
        drive, rel = os.path.splitdrive(self)
        return self.__class__(drive), rel
 
    def splitext(self):
        """ p.splitext() -> Return (p.stripext(), p.ext).
 
Split the filename extension from this path and return
the two parts. Either part may be empty.
 
The extension is everything from '.' to the end of the
last path segment. This has the property that if
(a, b) == p.splitext(), then a + b == p.
"""
        filename, ext = os.path.splitext(self)
        return self.__class__(filename), ext
 
    def stripext(self):
        """ p.stripext() -> Remove one file extension from the path.
 
For example, path('/home/guido/python.tar.gz').stripext()
returns path('/home/guido/python.tar').
"""
        return self.splitext()[0]
 
    if hasattr(os.path, 'splitunc'):
        def splitunc(self):
            unc, rest = os.path.splitunc(self)
            return self.__class__(unc), rest
 
        def _get_uncshare(self):
            unc, r = os.path.splitunc(self)
            return self.__class__(unc)
 
        uncshare = property(
            _get_uncshare, None, None,
            """ The UNC mount point for this path.
This is empty for paths on local drives. """)
 
    def joinpath(self, *args):
        """ Join two or more path components, adding a separator
character (os.sep) if needed. Returns a new path
object.
"""
        return self.__class__(os.path.join(self, *args))
 
    def splitall(self):
        r""" Return a list of the path components in this path.
 
The first item in the list will be a path. Its value will be
either os.curdir, os.pardir, empty, or the root directory of
this path (for example, '/' or 'C:\\'). The other items in
the list will be strings.
 
path.path.joinpath(*result) will yield the original path.
"""
        parts = []
        loc = self
        while loc != os.curdir and loc != os.pardir:
            prev = loc
            loc, child = prev.splitpath()
            if loc == prev:
                break
            parts.append(child)
        parts.append(loc)
        parts.reverse()
        return parts
 
    def relpath(self):
        """ Return this path as a relative path,
based from the current working directory.
"""
        cwd = self.__class__(os.getcwd())
        return cwd.relpathto(self)
 
    def relpathto(self, dest):
        """ Return a relative path from self to dest.
 
If there is no relative path from self to dest, for example if
they reside on different drives in Windows, then this returns
dest.abspath().
"""
        origin = self.abspath()
        dest = self.__class__(dest).abspath()
 
        orig_list = origin.normcase().splitall()
        # Don't normcase dest! We want to preserve the case.
        dest_list = dest.splitall()
 
        if orig_list[0] != os.path.normcase(dest_list[0]):
            # Can't get here from there.
            return dest
 
        # Find the location where the two paths start to differ.
        i = 0
        for start_seg, dest_seg in zip(orig_list, dest_list):
            if start_seg != os.path.normcase(dest_seg):
                break
            i += 1
 
        # Now i is the point where the two paths diverge.
        # Need a certain number of "os.pardir"s to work up
        # from the origin to the point of divergence.
        segments = [os.pardir] * (len(orig_list) - i)
        # Need to add the diverging part of dest_list.
        segments += dest_list[i:]
        if len(segments) == 0:
            # If they happen to be identical, use os.curdir.
            relpath = os.curdir
        else:
            relpath = os.path.join(*segments)
        return self.__class__(relpath)
 
    # --- Listing, searching, walking, and matching
 
    def listdir(self, pattern=None):
        """ D.listdir() -> List of items in this directory.
 
Use D.files() or D.dirs() instead if you want a listing
of just files or just subdirectories.
 
The elements of the list are path objects.
 
With the optional 'pattern' argument, this only lists
items whose names match the given pattern.
"""
        names = os.listdir(self)
        if pattern is not None:
            names = fnmatch.filter(names, pattern)
        return [self / child for child in names]
 
    def dirs(self, pattern=None):
        """ D.dirs() -> List of this directory's subdirectories.
 
The elements of the list are path objects.
This does not walk recursively into subdirectories
(but see path.walkdirs).
 
With the optional 'pattern' argument, this only lists
directories whose names match the given pattern. For
example, d.dirs('build-*').
"""
        return [p for p in self.listdir(pattern) if p.isdir()]
 
    def files(self, pattern=None):
        """ D.files() -> List of the files in this directory.
 
The elements of the list are path objects.
This does not walk into subdirectories (see path.walkfiles).
 
With the optional 'pattern' argument, this only lists files
whose names match the given pattern. For example,
d.files('*.pyc').
"""
        
        return [p for p in self.listdir(pattern) if p.isfile()]
 
    def walk(self, pattern=None, errors='strict'):
        """ D.walk() -> iterator over files and subdirs, recursively.
 
The iterator yields path objects naming each child item of
this directory and its descendants. This requires that
D.isdir().
 
This performs a depth-first traversal of the directory tree.
Each directory is returned just before all its children.
 
The errors= keyword argument controls behavior when an
error occurs. The default is 'strict', which causes an
exception. The other allowed values are 'warn', which
reports the error via warnings.warn(), and 'ignore'.
"""
        if errors not in ('strict', 'warn', 'ignore'):
            raise ValueError("invalid errors parameter")
 
        try:
            childList = self.listdir()
        except Exception:
            if errors == 'ignore':
                return
            elif errors == 'warn':
                warnings.warn(
                    "Unable to list directory '%s': %s"
                    % (self, sys.exc_info()[1]),
                    TreeWalkWarning)
                return
            else:
                raise
 
        for child in childList:
            if pattern is None or child.fnmatch(pattern):
                yield child
            try:
                isdir = child.isdir()
            except Exception:
                if errors == 'ignore':
                    isdir = False
                elif errors == 'warn':
                    warnings.warn(
                        "Unable to access '%s': %s"
                        % (child, sys.exc_info()[1]),
                        TreeWalkWarning)
                    isdir = False
                else:
                    raise
 
            if isdir:
                for item in child.walk(pattern, errors):
                    yield item
 
    def walkdirs(self, pattern=None, errors='strict'):
        """ D.walkdirs() -> iterator over subdirs, recursively.
 
With the optional 'pattern' argument, this yields only
directories whose names match the given pattern. For
example, mydir.walkdirs('*test') yields only directories
with names ending in 'test'.
 
The errors= keyword argument controls behavior when an
error occurs. The default is 'strict', which causes an
exception. The other allowed values are 'warn', which
reports the error via warnings.warn(), and 'ignore'.
"""
        if errors not in ('strict', 'warn', 'ignore'):
            raise ValueError("invalid errors parameter")
 
        try:
            dirs = self.dirs()
        except Exception:
            if errors == 'ignore':
                return
            elif errors == 'warn':
                warnings.warn(
                    "Unable to list directory '%s': %s"
                    % (self, sys.exc_info()[1]),
                    TreeWalkWarning)
                return
            else:
                raise
 
        for child in dirs:
            if pattern is None or child.fnmatch(pattern):
                yield child
            for subsubdir in child.walkdirs(pattern, errors):
                yield subsubdir
 
    def walkfiles(self, pattern=None, errors='strict'):
        """ D.walkfiles() -> iterator over files in D, recursively.
 
The optional argument, pattern, limits the results to files
with names that match the pattern. For example,
mydir.walkfiles('*.tmp') yields only files with the .tmp
extension.
"""
        if errors not in ('strict', 'warn', 'ignore'):
            raise ValueError("invalid errors parameter")
 
        try:
            childList = self.listdir()
        except Exception:
            if errors == 'ignore':
                return
            elif errors == 'warn':
                warnings.warn(
                    "Unable to list directory '%s': %s"
                    % (self, sys.exc_info()[1]),
                    TreeWalkWarning)
                return
            else:
                raise
 
        for child in childList:
            try:
                isfile = child.isfile()
                isdir = not isfile and child.isdir()
            except:
                if errors == 'ignore'