/
os_use.py
1404 lines (1083 loc) · 39.7 KB
/
os_use.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 python3
"""
prototype::
date = 2016-04-06
The main feature of this module is the class ``PPath`` which is an enhanced
version of the standard class ``pathlib.Path`` that allows to manipulate easily
paths and as a consequence files and folders.
There are also other small useful functions like ``runthis`` that really
simplify the use of a command line from ¨python codes.
"""
import os
import pathlib
import platform
import re
import shlex
import shutil
from subprocess import (
check_call,
check_output
)
# -------------------- #
# -- SAFE CONSTANTS -- #
# -------------------- #
OS_MAC = "mac"
OS_LINUX = "linux"
OS_WIN = "windows"
# Sources for the regex:
# * http://stackoverflow.com/a/430781/4589608
# * http://stackoverflow.com/a/30439865/4589608
# * http://stackoverflow.com/a/817117/4589608
# * http://stackoverflow.com/a/20294987/4589608
ALL_DIR_TAGS = DIR_TAG, DIR_OTHERS_TAG \
= "dir", "dir_others"
ALL_FILE_TAGS = FILE_TAG, FILE_OTHERS_TAG \
= "file", "file_others"
FILE_DIR_OTHERS_NAME = "..."
NOT_QUERY = "not"
FILE_DIR_QUERY = set([FILE_TAG, DIR_TAG])
ALL_DISPLAY, XTRA_DISPLAY = "all", "xtra"
REGPATH_QUERIES = set([
DIR_TAG, FILE_TAG,
NOT_QUERY,
ALL_DISPLAY, XTRA_DISPLAY
])
LONG_REGPATH_QUERIES = {x[0]: x for x in REGPATH_QUERIES}
RE_SPECIAL_CHARS = re.compile(
r"(?<!\\)((?:\\\\)*)((\*+)|(@)|(×)|(\.))"
)
REGPATH_TO_REGEX = {
'**': ".+",
'.' : r"\.",
'@' : ".",
'×' : "*",
}
REGPATH_SPE_CHARS = list(REGPATH_TO_REGEX) + ["*"]
REGPATH_TO_REGEX['\\'] = "[^\\]+"
REGPATH_TO_REGEX['/'] = "[^/]+"
# ------------------- #
# -- GENERAL INFOS -- #
# ------------------- #
SEP = os.sep
def pathenv():
"""
prototype::
return = str ;
the variable ``PATH`` that contains paths of executables known
by your OS
"""
return os.getenv('PATH')
def system():
"""
prototype::
return = str ;
the name, in lower case, of the OS used (possible names can be
"windows", "mac", "linux" and also "java")
"""
osname = platform.system()
if not osname:
raise SystemError("the operating sytem can't be found.")
if osname == 'Darwin':
return OS_MAC
else:
return osname.lower()
# -------------------------------- #
# -- CHANGING CURRENT DIRECTORY -- #
# -------------------------------- #
class cd:
"""
prototype::
type = cls ;
this class i a context manager that allows to easily change the
current directory as this can be done using term::``cd`` in a ¨unix
system, or term::``chdir`` in a ¨win sytem
arg-attr = PPath: ppath ;
this gives the path where to go
Let's suppose that we have the following directory having the absolute path
path::``/Users/projetmbc/basic_dir`` in a ¨unix system.
dir::
+ basic_dir
* latex_1.tex
* latex_2.tex
* python_1.py
* python_2.py
* python_3.py
* python_4.py
* text_1.txt
* text_2.txt
* text_3.txt
+ empty_dir
+ sub_dir
* code_A.py
* code_B.py
* slide_A.pdf
* slide_B.pdf
+ sub_sub_dir
* doc.pdf
In the following ¨unix example, the use of ``subprocess.call("ls")`` is similar
to use term::``ls`` directly in a ¨unix terminal so as to have the list of all
files and directories directly contained in a the current folder. As you can
see, the lists of files and folders correspond to the current directory choosen
with the class ``cd``.
pyterm::
>>> import subprocess
>>> from mistool.os_use import cd
>>> with cd("/Users/projetmbc/basic_dir"):
... subprocess.call("ls")
empty_dir python_1.py python_4.py text_2.txt
latex_1.tex python_2.py sub_dir text_3.txt
latex_2.tex python_3.py text_1.txt
>>> with cd("/Users/projetmbc/basic_dir/sub_dir"):
... subprocess.call("ls")
code_A.py slide_A.pdf sub_sub_dir
code_B.py slide_B.pdf
info::
All the code comes from
cf::``this post ; http://stackoverflow.com/a/13197763/4589608``.
"""
def __init__(self, ppath):
self._newstrpath = str(ppath.normpath)
self._tag = ""
def __enter__(self):
self._savedpath = os.getcwd()
os.chdir(self._newstrpath)
def __exit__(self, etype, value, traceback):
os.chdir(self._savedpath)
# ------------------------ #
# -- OUR ENHANCED CLASS -- #
# ------------------------ #
# -- FOR THE REGPATHS -- #
def regexify(pattern, sep = "/"):
"""
prototype::
arg = str: pattern ;
``pattern`` is a regpath pattern using a syntax which tries to catch
the best of the regex and the Unix-glob syntaxes
arg = str: sep = "/" ;
this indicates an ¨os like separator
return = str ;
a regex uncompiled version of ``pattern``.
====================
Some examples of use
====================
The next section gives all the difference between the regpath patterns and the
regexes of ¨python.
Let suppose fisrt that we want to find paths without any ``/`` the default
value of the argument ``sep`` that finish with either path::``.py`` or
path::``.txt``. The code below shows how ``regexify`` gives easily an
uncompiled regex pattern to do such searches.
pyterm::
>>> from mistool.os_use import regexify
>>> print(regexify("*.(py|txt)"))
[^/]+\.(py|txt)
Let suppose now that we want to find paths that finish with either
path::``.py`` or path::``.txt``, and that can also be virtually or really
found recursivly when walking in a directory. Here is how to use ``regexify``.
pyterm::
>>> from mistool.os_use import regexify
>>> print(regexify("**.(py|txt)"))
.+\.(py|txt)
=============================
A Unix-glob like regex syntax
=============================
Here are the only differences between the Unix-glob like regex syntax with the
Unix-glob syntax and the traditional regexes.
1) ``*`` indicates one ore more characters except the separator of the OS.
This corresponds to the regex regex::``[^\\]+`` or regex::``[^/]+``
regarding to the OS is Windows or Unix.
2) ``**`` indicates one ore more characters even the separator of the OS.
This corresponds to the regex regex::``.+``.
3) ``.`` is not a special character, this is just a point. This corresponds
to regex::``\.`` in regexes.
4) The multiplication symbol ``×`` is the equivalent of regex::``*`` in
regexes. This allows to indicate zero or more repetitions.
5) ``@`` is the equivalent of regex::``.`` in regexes. This allows to
indicate any single character except a newline.
6) ``\`` is an escaping for special character. For example, you have to use
a double backslash ``\\`` to indicate the Windows separator ``\``.
"""
onestar2regex = REGPATH_TO_REGEX[sep]
newpattern = ""
lastpos = 0
for m in RE_SPECIAL_CHARS.finditer(pattern):
spechar = m.group()
if spechar not in REGPATH_SPE_CHARS:
raise ValueError("too much consecutive stars ''*''")
spechar = REGPATH_TO_REGEX.get(spechar, onestar2regex)
newpattern += pattern[lastpos:m.start()] + spechar
lastpos = m.end()
newpattern += pattern[lastpos:]
return newpattern
def regpath2meta(regpath, sep = "/", regexit = True):
"""
prototype::
see = regexify
arg = str: regpath ;
``regpath`` uses a syntax trying to catch the best of the regex and
the Unix-glob syntaxes with also some little extra queries
arg = str: sep = "/" ;
this indicates an ¨os like separator
arg = bool: regexit = True ;
``regexit`` allows to have the regex version of ``regpath``
return = tuple(set(str): queries, str: pattern) ;
``queries`` give extra infos about the kind of objects to "search",
and ``pattern`` is a "searching pattern" which is in regex
uncompiled version if ``regexit = True``.
=====================
What is a "regpath" ?
=====================
A "regpath" allows to use all the power of regexes with the easy to use special
characters of the Unix-glob syntax, and it offers also some additional query
features.
The syntax can be either "regex_glob_part" or "query_part::regex_glob_part"
where "query_part" and "regex_glob_part" must follow some rules explained in
the following sections.
Here are some exemples on a ¨unix system.
pyterm::
>>> from mistool.os_use import PPath
>>> path = PPath("")
>>> print(path.regpath2meta("*.(py|txt)"))
({'dir', 'file'}, '[^/]+\\.(py|txt)')
>>> print(path.regpath2meta(regpath = "*.(py|txt)", regexit = False))
({'dir', 'file'}, '*.(py|txt)')
>>> print(path.regpath2meta("all file::**.py"))
({'all', 'file'}, '.+\\.py')
In the outputs printed, `{'dir', 'file'}` indicates to look only for visible
files and directories, whereas `{'all', 'file'}` asks to keep also invisible
files, i.e. files having a name starting with a point.
=================================
The regex and Unix-glob like part
=================================
See the documentation of the function ``regexify``.
==============
The query part
==============
Before two double points, you can use the following queries separated by
spaces.
1) ``not`` is very useful because it allows simply to look for something
that does not match the pattern (you have to know that direct negation with
regexes can be messy).
2) ``file`` asks to keep only files.
3) ``dir`` asks to keep only folders.
4) ``all`` asks to keep also the hidden files and folders. This ones have
a name begining with a point.
5) ``all file`` asks to only keep files even the hidden ones. You can also
use ``all dir``.
6) ``relative`` indicates that the pattern after ``::`` is relatively to
the current directory and not to a absolute path.
7) ``xtra`` asks to keep folder with some files not matching a regpath.
Extra informations are given by the hidden attribut ``_tag`` (this feature
is used by the class ``term_use.DirView``).
For example, to keep only the ¨python files, in a folder or not, just use
``"file::**.py"``. This is not the same that ``"**.py"`` which will also catch
folders with a name finishing by path::``.py`` (that is legal).
info::
For each query, you can use just its initial letter. For example, ``f`` is
a shortcut for ``file``, and ``a f`` is the same as ``all file``.
"""
queries, *pattern = regpath.split("::")
if len(pattern) > 1:
raise ValueError("too much \"::\" in the regpath.")
# Two pieces
if pattern:
pattern = pattern[0]
queries = set(
LONG_REGPATH_QUERIES.get(x.strip(), x.strip())
for x in queries.split(" ")
if x.strip()
)
if not queries <= REGPATH_QUERIES:
raise ValueError("illegal filter(s) in the regpath.")
# One single piece
else:
queries, pattern = FILE_DIR_QUERY, queries
# The queries "file" and "dir" are not used.
if FILE_TAG not in queries and DIR_TAG not in queries:
queries |= FILE_DIR_QUERY
# The regex uncompiled version : we just do replacing by taking care of
# the escaping character. We play with regexes to do that.
#
# << Warning : >> ***, ****, ... are not allowed !
if regexit:
pattern = "^{0}$".format(
regexify(
pattern = pattern,
sep =sep
)
)
return queries, pattern
# Sublcassing ``pathlib.Path`` is not straightforward ! The following post gives
# the less ugly way to do that :
# * http://stackoverflow.com/a/34116756/4589608
class PPath(type(pathlib.Path())):
"""
prototype::
see = pathlib.Path
type = cls ;
this class adds some functionalities to the standard class
``pathlib.Path``
warning::
The method ``walk`` of this class uses an hidden attribut ``_tag`` which has
no meaning outside the scope of the method ``walk``.
"""
# -- ABOUT -- #
def is_empty(self):
"""
prototype::
return = bool ;
if ``PPath`` is not an existing directory an error is raised, but
if the ``PPath`` points to an empty directory, ``False`` is
returned, otherwise that is ``True`` which is returned
"""
if not self.is_dir():
raise NotADirectoryError(
"the following path does not point to an existing directory :"
"\n + {0}".format(self)
)
for onepath in self.walk():
return False
return True
def is_protected(self):
"""
prototype::
return = bool ;
if the path doe not point to an existing file or folder, an
``OSError`` error is raised,
if the path is the one of a folder, the answer returned is
``True`` for a modifiable directory and ``False`` othrewise,
and finally if the path points to a file, then that is its
parent folder which is tested
"""
if self.is_file():
ppath = self.parent
elif self.is_dir():
ppath = self
else:
raise FileNotFoundError(
"the following path doesn't point to something inside an "
"existing directory :\n + {0}".format(self)
)
# Source :
# * http://stackoverflow.com/q/2113427/4589608
return not os.access(
path = str(ppath),
mode = os.W_OK | os.X_OK
)
@property
def depth(self):
"""
prototype::
see = self.depth_in
return = int ;
the absolute depth of a path
Here is an example of use.
pyterm::
>>> from mistool.os_use import PPath
>>> path = PPath("/Users/projetmbc/source/misTool/os_use.py")
>>> print(path.depth)
4
"""
return len(self.parents) - 1
@property
def ext(self):
"""
prototype::
see = self.with_ext
return = str ;
the extension of the path
Here is a small example of use where you can see that the attribut ``ext`` is
just the value of the attribut ``suffix``, from ``pathlib.Path``, but without
the leading point.
pyterm::
>>> from mistool.os_use import PPath
>>> path = PPath("dir/subdir/file.txt")
>>> print(path.ext)
'txt'
>>> print(path.suffix)
'.txt'
"""
# An extension is a suffix without the leading point.
return self.suffix[1:]
# -- CHANGING A PATH -- #
def with_ext(self, ext):
"""
prototype::
arg = str: ext ;
value of the extension
return = PPath ;
a new path obtained from the current path by adding or changing
the extension using the value of ``ext``
Here are two examples.
pyterm::
>>> from mistool.os_use import PPath
>>> path = PPath("dir/subdir")
>>> path.with_ext("ext")
PPath('dir/subdir.ext')
>>> path = PPath("dir/subdir/file.txt")
>>> path.with_ext("ext")
PPath('dir/subdir/file.ext')
"""
if ext:
ext = "." + ext
return self.with_suffix(ext)
@property
def normpath(self):
"""
prototype::
return = PPath ;
a new path obtained from the current path by interpreting the
leading shortcut path::``~``, and the shortcuts for relative
paths like path::``/../`` that are used to go higher in the tree
structure
Here is an example made on the ¨mac of the author of ¨mistool where the user's
folder is path::``/Users/projetmbc``.
pyterm::
>>> from mistool.os_use import PPath
>>> path = PPath("~/dir_1/dir_2/dir_3/../../file.txt")
>>> path.normpath
PPath('/Users/projetmbc/dir_1/file.txt')
"""
return PPath(
os.path.normpath(
os.path.expanduser(str(self))
)
)
@property
def shortpath(self):
"""
prototype::
return = PPath ;
a new path obtained from the current path by trying to use the
leading shortcut path::``~``, and by intepreting the shortcuts
path::``/../`` used to go higher in the tree structure
Here is an example made on the Mac of the author of ¨mistool. In that case
path::``/Users/projetmbc`` is the user's folder.
pyterm::
>>> from mistool.os_use import PPath
>>> path = PPath("/Users/projetmbc/dir_1/dir_2/dir_3/../../file.txt")
>>> path.shortpath
PPath('~/dir_1/file.txt')
"""
path = os.path.normpath(os.path.expanduser(str(self)))
userpath = os.path.expanduser("~") + self._flavour.sep
if path.startswith(userpath):
path = "~" + self._flavour.sep + path[len(userpath):]
return PPath(path)
# -- COMPARING PATHS -- #
def common_with(self, *args):
"""
prototype::
see = self.__and__
args = PPath ;
the arguments can be given separated by comas, or in list, or in
a tuple
return = PPath ;
a new path which corresponds to the "smaller common folder" of
the current path and the other ones given in arguments
In the following example, the two last calls to ``common_with`` show that you
can either use a list or a tuple of paths, or instead several arguments for the
different paths.
pyterm::
>>> from mistool.os_use import PPath
>>> path = PPath("/Users/projetmbc/source/doc")
>>> path_1 = PPath("/Users/projetmbc/README")
>>> path_2 = PPath("/Users/projetmbc/source/misTool/os_use.py")
>>> path_danger = PPath("/NoUser/projects")
>>> path.common_with(path_1)
PPath('/Users/projetmbc')
>>> path.common_with(path_2)
PPath('/Users/projetmbc/source')
>>> path.common_with(path_danger)
PPath('/')
>>> path.common_with(path_1, path_2)
PPath('/Users/projetmbc')
>>> path.common_with([path_1, path_2])
PPath('/Users/projetmbc')
You can also use the magic method ``&`` as a shortcut to ``common_with``. Some
of the preceding examples becomes then the following ones.
pyterm::
>>> path & path_1
PPath('/Users/projetmbc')
>>> path & path_1 & path_2
PPath('/Users/projetmbc')
>>> path & [path_1, path_2]
PPath('/Users/projetmbc')
info::
The use of ``&`` was inspired by the analogy between the logical "AND" and
the intersection of sets.
"""
commonparts = list(self.parts)
paths = []
for onearg in args:
if isinstance(onearg, list):
paths += onearg
elif isinstance(onearg, tuple):
paths += list(onearg)
else:
paths.append(onearg)
for path in paths:
i = 0
for common, current in zip(commonparts, path.parts):
if common == current:
i += 1
else:
break
commonparts = commonparts[:i]
if not commonparts:
break
commonpath = pathlib.Path("")
for part in commonparts:
commonpath /= part
return commonpath
def __and__(self, paths):
"""
prototype::
see = self.common_with
arg = PPath , list(PPath) , tuple(PPath): paths
return = PPath ;
a new path which corresponds to the "smaller common folder" of
the current path and the other ones given in arguments
This magic method allows to use ``path & paths`` instead of the long version
``path.common_with(paths)`` where ``paths`` can be either a single path, or
a list or a tuple of paths.
"""
return self.common_with(paths)
def __sub__(self, path):
"""
prototype::
arg = PPath: path
return = PPath ;
a new path which corresponds to the relative path of the current
one regarding to the path given in the argument ``path``
This magic method allows to use ``path - anotherpath`` instead of the long
version ``path.relative_to(anotherpath)`` given by ``pathlib.Path``. Here are
some examples of use.
pyterm::
>>> from mistool.os_use import PPath
>>> main = PPath("/Users/projetmbc")
>>> path_1 = PPath("/Users/projetmbc/README")
>>> path_2 = PPath("/Users/projetmbc/source/misTool/os_use.py")
>>> path_1 - main
PPath('README')
>>> path_2 - main
PPath('source/misTool/os_use.py')
>>> path_2 - path_1
Traceback (most recent call last):
[...]
ValueError: '/Users/projetmbc/source/misTool/os_use.py' does not start with
'/Users/projetmbc/README'
"""
return self.relative_to(path.normpath)
def depth_in(self, path):
"""
prototype::
arg = PPath: path
return = PPath ;
the depth of the current path regarding to the one given in the
argument ``path``
Here are some examples of use.
pyterm::
>>> from mistool.os_use import PPath
>>> main = PPath("/Users/projetmbc")
>>> path_1 = PPath("/Users/projetmbc/README")
>>> path_2 = PPath("/Users/projetmbc/source/misTool/os_use.py")
>>> path_pb = PPath("/NoUser/projects")
>>> print(path_1.depth_in(main))
0
>>> print(path_2.depth_in(main))
2
>>> print(path_pb.depth_in(main))
Traceback (most recent call last):
[...]
ValueError: '/NoUser/projects' does not start with '/Users/projetmbc'
"""
return len(self.relative_to(path.normpath).parts) - 1
# -- WALK AND SEE -- #
def see(self):
"""
prototype::
action = this method shows one directory or one file in the OS environment
by trying to call an associated application
"""
# Nothing to open...
if not self.is_file() and not self.is_dir():
raise FileNotFoundError(
"the following path points nowhere:"
"\n + {0}".format(self)
)
# We need the **string** long normalized version of the path.
strpath = str(self.normpath)
# Each OS has its own method.
osname = system()
# Windows
if osname == OS_WIN:
if self.is_file():
os.startfile(strpath)
else:
check_call(args = ['explorer', strpath])
# Mac
elif osname == OS_MAC:
check_call(args = ['open', strpath])
# Linux
#
# Source :
# * http://forum.ubuntu-fr.org/viewtopic.php?pid=3952590#p3952590
elif osname == OS_LINUX:
check_call(args = ['xdg-open', strpath])
# Unknown method...
else:
raise OSError(
"the opening of the following file in the OS "
"<< {0} >> is not supported \n + {0}".format(
osname,
self
)
)
def walk(self, regpath = "**"):
"""
prototype::
see = regpath2meta
arg = str: regpath = "**" ;
this is a string that follows some rules named regpath rules
yield = PPath;
the ``PPath`` are absolute paths of files and directories matching
the "regpath" pattern (in each folder, the files are always yield
before the sub folders and the search is always relative)
Let's suppose that we have the following directory having the absolute path
path::``/Users/projetmbc/basic_dir`` in a ¨unix system.
dir::
+ basic_dir
* latex_1.tex
* latex_2.tex
* python_1.py
* python_2.py
* python_3.py
* python_4.py
* text_1.txt
* text_2.txt
* text_3.txt
+ empty_dir
+ sub_dir
* code_A.py
* code_B.py
* slide_A.pdf
* slide_B.pdf
+ sub_sub_dir
* doc.pdf
By default, you will have from lower depth to higher files following by folders.
Let's see this in action.
pyterm::
>>> from mistool.os_use import PPath
>>> folder = PPath("/Users/projetmbc/basic_dir")
>>> for p in folder.walk():
... print("+", p)
...
+ /Users/projetmbc/basic_dir/latex_1.tex
+ /Users/projetmbc/basic_dir/latex_2.tex
+ /Users/projetmbc/basic_dir/python_1.py
+ /Users/projetmbc/basic_dir/python_2.py
+ /Users/projetmbc/basic_dir/python_3.py
+ /Users/projetmbc/basic_dir/python_4.py
+ /Users/projetmbc/basic_dir/text_1.txt
+ /Users/projetmbc/basic_dir/text_2.txt
+ /Users/projetmbc/basic_dir/text_3.txt
+ /Users/projetmbc/basic_dir/empty_dir
+ /Users/projetmbc/basic_dir/sub_dir
+ /Users/projetmbc/basic_dir/sub_dir/code_A.py
+ /Users/projetmbc/basic_dir/sub_dir/code_B.py
+ /Users/projetmbc/basic_dir/sub_dir/slide_A.pdf
+ /Users/projetmbc/basic_dir/sub_dir/slide_B.pdf
+ /Users/projetmbc/basic_dir/sub_dir/sub_sub_dir
+ /Users/projetmbc/basic_dir/sub_dir/sub_sub_dir/doc.pdf
Here are others easy examples where the regpath ``"*"`` is for a non-recursive
search contrary to the regpath ``"**"`` which is the default value (see the
preceding example). Just take a look at the documentation of the method
``regpath2meta`` for more ¨infos about regpaths.
pyterm::
>>> from mistool.os_use import PPath
>>> folder = PPath("/Users/projetmbc/basic_dir")
>>> for p in folder.walk("dir::**"):
... print("+", p)
...
+ /Users/projetmbc/basic_dir/empty_dir
+ /Users/projetmbc/basic_dir/sub_dir
+ /Users/projetmbc/basic_dir/sub_dir/sub_sub_dir
>>> for p in folder.walk("file::**.py"):
... print("+", p)
...
+ /Users/projetmbc/basic_dir/python_1.py
+ /Users/projetmbc/basic_dir/python_2.py
+ /Users/projetmbc/basic_dir/python_3.py
+ /Users/projetmbc/basic_dir/python_4.py
+ /Users/projetmbc/basic_dir/sub_dir/code_A.py
+ /Users/projetmbc/basic_dir/sub_dir/code_B.py
>>> for p in folder.walk("file::*.py"):
... print("+", p)
...
+ /Users/projetmbc/basic_dir/python_1.py
+ /Users/projetmbc/basic_dir/python_2.py
+ /Users/projetmbc/basic_dir/python_3.py
+ /Users/projetmbc/basic_dir/python_4.py
info::
If you want to see the existing files and/or folders that do not match the
regpath, you will have to use the query ``xtra`` together with the "hidden"
attribut ``_tag`` (the class ``DirView`` of the module ``term_use`` uses
this). Here is an example of use.
pyterm::
>>> from mistool.os_use import PPath
>>> folder = PPath("/Users/projetmbc/dir")
>>> for p in folder.walk("xtra file::**.py"):
... print("+", p._tag, ">>>", p)
...
+ file >>> /Users/projetmbc/basic_dir/python_1.py
+ file >>> /Users/projetmbc/basic_dir/python_2.py
+ file >>> /Users/projetmbc/basic_dir/python_3.py
+ file >>> /Users/projetmbc/basic_dir/python_4.py
+ file_others >>> /Users/projetmbc/basic_dir/...
+ file >>> /Users/projetmbc/basic_dir/sub_dir/code_A.py
+ file >>> /Users/projetmbc/basic_dir/sub_dir/code_B.py
+ file_others >>> /Users/projetmbc/basic_dir/sub_dir/...
+ file_others >>> /Users/projetmbc/basic_dir/sub_dir/sub_sub_dir/...
The special names are stored in the following global string variables to be
used so as to avoid typing errors.
* ``FILE_TAG``
* ``FILE_OTHERS_TAG``
* ``DIR_TAG``
* ``DIR_OTHERS_TAG``
"""
# Do we have an existing directory ?
if not self.is_dir():
raise NotADirectoryError(
"the following path doesn't point to a directory :"
"\n + {0}".format(self)
)
# Metadatas and the normal regex
queries, pattern = regpath2meta(
regpath = regpath,
sep = self._flavour.sep
)
maindir = str(self)
notkeepdir = DIR_TAG not in queries
notkeepfile = FILE_TAG not in queries
notkeepall = ALL_DISPLAY not in queries
addextra = XTRA_DISPLAY in queries
regex_obj = re.compile(pattern)
# Matching or non-matching, that is the question !
if NOT_QUERY in queries:
match = lambda x: not regex_obj.match(x)
else:
match = lambda x: regex_obj.match(x)
# Let's walk
for root, dirs, files in os.walk(maindir):
# The matching paths
for tag, strpaths in [
(FILE_TAG, files),
(DIR_TAG, dirs)