Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 35.3k
Expand file tree
/
Copy pathos.py
More file actions
Latest commit
1069 lines (898 loc) · 36.6 KB
/
Copy pathos.py
File metadata and controls
1069 lines (898 loc) · 36.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
r"""OS routines for NT or Posix depending on what system we're on.
This exports:
- all functions from posix or nt, e.g. unlink, stat, etc.
- os.path is either posixpath or ntpath
- os.name is either 'posix' or 'nt'
- os.curdir is a string representing the current directory (always '.')
- os.pardir is a string representing the parent directory (always '..')
- os.sep is the (or a most common) pathname separator ('/' or '\\')
- os.extsep is the extension separator (always '.')
- os.altsep is the alternate pathname separator (None or '/')
- os.pathsep is the component separator used in $PATH etc
- os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
- os.defpath is the default search path for executables
- os.devnull is the file path of the null device ('/dev/null', etc.)
Programs that import and use 'os' stand a better chance of being
portable between different platforms. Of course, they must then
only use functions that are defined by all platforms (e.g., unlink
and opendir), and leave all pathname manipulation to os.path
(e.g., split and join).
"""
#'
importabc
importsys, errno
importstatasst
_names=sys.builtin_module_names
# Note: more names are added to __all__ later.
__all__= ["altsep", "curdir", "pardir", "sep", "pathsep", "linesep",
"defpath", "name", "path", "devnull", "SEEK_SET", "SEEK_CUR",
"SEEK_END", "fsencode", "fsdecode", "get_exec_path", "fdopen",
"popen", "extsep"]
def_exists(name):
returnnameinglobals()
def_get_exports_list(module):
try:
returnlist(module.__all__)
exceptAttributeError:
return [nfornindir(module) ifn[0] !='_']
# Any new dependencies of the os module and/or changes in path separator
# requires updating importlib as well.
if'posix'in_names:
name='posix'
linesep='\n'
fromposiximport*
try:
fromposiximport_exit
__all__.append('_exit')
exceptImportError:
pass
importposixpathaspath
try:
fromposiximport_have_functions
exceptImportError:
pass
importposix
__all__.extend(_get_exports_list(posix))
delposix
elif'nt'in_names:
name='nt'
linesep='\r\n'
fromntimport*
try:
fromntimport_exit
__all__.append('_exit')
exceptImportError:
pass
importntpathaspath
importnt
__all__.extend(_get_exports_list(nt))
delnt
try:
fromntimport_have_functions
exceptImportError:
pass
else:
raiseImportError('no os specific module found')
sys.modules['os.path'] =path
fromos.pathimport (curdir, pardir, sep, pathsep, defpath, extsep, altsep,
devnull)
del_names
if_exists("_have_functions"):
_globals=globals()
def_add(str, fn):
if (fnin_globals) and (strin_have_functions):
_set.add(_globals[fn])
_set=set()
_add("HAVE_FACCESSAT", "access")
_add("HAVE_FCHMODAT", "chmod")
_add("HAVE_FCHOWNAT", "chown")
_add("HAVE_FSTATAT", "stat")
_add("HAVE_FUTIMESAT", "utime")
_add("HAVE_LINKAT", "link")
_add("HAVE_MKDIRAT", "mkdir")
_add("HAVE_MKFIFOAT", "mkfifo")
_add("HAVE_MKNODAT", "mknod")
_add("HAVE_OPENAT", "open")
_add("HAVE_READLINKAT", "readlink")
_add("HAVE_RENAMEAT", "rename")
_add("HAVE_SYMLINKAT", "symlink")
_add("HAVE_UNLINKAT", "unlink")
_add("HAVE_UNLINKAT", "rmdir")
_add("HAVE_UTIMENSAT", "utime")
supports_dir_fd=_set
_set=set()
_add("HAVE_FACCESSAT", "access")
supports_effective_ids=_set
_set=set()
_add("HAVE_FCHDIR", "chdir")
_add("HAVE_FCHMOD", "chmod")
_add("HAVE_FCHOWN", "chown")
_add("HAVE_FDOPENDIR", "listdir")
_add("HAVE_FEXECVE", "execve")
_set.add(stat) # fstat always works
_add("HAVE_FTRUNCATE", "truncate")
_add("HAVE_FUTIMENS", "utime")
_add("HAVE_FUTIMES", "utime")
_add("HAVE_FPATHCONF", "pathconf")
if_exists("statvfs") and_exists("fstatvfs"): # mac os x10.3
_add("HAVE_FSTATVFS", "statvfs")
supports_fd=_set
_set=set()
_add("HAVE_FACCESSAT", "access")
# Some platforms don't support lchmod(). Often the function exists
# anyway, as a stub that always returns ENOSUP or perhaps EOPNOTSUPP.
# (No, I don't know why that's a good design.) ./configure will detect
# this and reject it--so HAVE_LCHMOD still won't be defined on such
# platforms. This is Very Helpful.
#
# However, sometimes platforms without a working lchmod() *do* have
# fchmodat(). (Examples: Linux kernel 3.2 with glibc 2.15,
# OpenIndiana 3.x.) And fchmodat() has a flag that theoretically makes
# it behave like lchmod(). So in theory it would be a suitable
# replacement for lchmod(). But when lchmod() doesn't work, fchmodat()'s
# flag doesn't work *either*. Sadly ./configure isn't sophisticated
# enough to detect this condition--it only determines whether or not
# fchmodat() minimally works.
#
# Therefore we simply ignore fchmodat() when deciding whether or not
# os.chmod supports follow_symlinks. Just checking lchmod() is
# sufficient. After all--if you have a working fchmodat(), your
# lchmod() almost certainly works too.
#
# _add("HAVE_FCHMODAT", "chmod")
_add("HAVE_FCHOWNAT", "chown")
_add("HAVE_FSTATAT", "stat")
_add("HAVE_LCHFLAGS", "chflags")
_add("HAVE_LCHMOD", "chmod")
if_exists("lchown"): # mac os x10.3
_add("HAVE_LCHOWN", "chown")
_add("HAVE_LINKAT", "link")
_add("HAVE_LUTIMES", "utime")
_add("HAVE_LSTAT", "stat")
_add("HAVE_FSTATAT", "stat")
_add("HAVE_UTIMENSAT", "utime")
_add("MS_WINDOWS", "stat")
supports_follow_symlinks=_set
del_set
del_have_functions
del_globals
del_add
# Python uses fixed values for the SEEK_ constants; they are mapped
# to native constants if necessary in posixmodule.c
# Other possible SEEK values are directly imported from posixmodule.c
SEEK_SET=0
SEEK_CUR=1
SEEK_END=2
# Super directory utilities.
# (Inspired by Eric Raymond; the doc strings are mostly his)
defmakedirs(name, mode=0o777, exist_ok=False):
"""makedirs(name [, mode=0o777][, exist_ok=False])
Super-mkdir; create a leaf directory and all intermediate ones. Works like
mkdir, except that any intermediate path segment (not just the rightmost)
will be created if it does not exist. If the target directory already
exists, raise an OSError if exist_ok is False. Otherwise no exception is
raised. This is recursive.
"""
head, tail=path.split(name)
ifnottail:
head, tail=path.split(head)
ifheadandtailandnotpath.exists(head):
try:
makedirs(head, mode, exist_ok)
exceptFileExistsError:
# Defeats race condition when another thread created the path
pass
cdir=curdir
ifisinstance(tail, bytes):
cdir=bytes(curdir, 'ASCII')
iftail==cdir: # xxx/newdir/. exists if xxx/newdir exists
return
try:
mkdir(name, mode)
exceptOSError:
# Cannot rely on checking for EEXIST, since the operating system
# could give priority to other errors like EACCES or EROFS
ifnotexist_okornotpath.isdir(name):
raise
defremovedirs(name):
"""removedirs(name)
Super-rmdir; remove a leaf directory and all empty intermediate
ones. Works like rmdir except that, if the leaf directory is
successfully removed, directories corresponding to rightmost path
segments will be pruned away until either the whole path is
consumed or an error occurs. Errors during this latter phase are
ignored -- they generally mean that a directory was not empty.
"""
rmdir(name)
head, tail=path.split(name)
ifnottail:
head, tail=path.split(head)
whileheadandtail:
try:
rmdir(head)
exceptOSError:
break
head, tail=path.split(head)
defrenames(old, new):
"""renames(old, new)
Super-rename; create directories as necessary and delete any left
empty. Works like rename, except creation of any intermediate
directories needed to make the new pathname good is attempted
first. After the rename, directories corresponding to rightmost
path segments of the old name will be pruned until either the
whole path is consumed or a nonempty directory is found.
Note: this function can fail with the new directory structure made
if you lack permissions needed to unlink the leaf directory or
file.
"""
head, tail=path.split(new)
ifheadandtailandnotpath.exists(head):
makedirs(head)
rename(old, new)
head, tail=path.split(old)
ifheadandtail:
try:
removedirs(head)
exceptOSError:
pass
__all__.extend(["makedirs", "removedirs", "renames"])
defwalk(top, topdown=True, onerror=None, followlinks=False):
"""Directory tree generator.
For each directory in the directory tree rooted at top (including top
itself, but excluding '.' and '..'), yields a 3-tuple
dirpath, dirnames, filenames
dirpath is a string, the path to the directory. dirnames is a list of
the names of the subdirectories in dirpath (excluding '.' and '..').
filenames is a list of the names of the non-directory files in dirpath.
Note that the names in the lists are just names, with no path components.
To get a full path (which begins with top) to a file or directory in
dirpath, do os.path.join(dirpath, name).
If optional arg 'topdown' is true or not specified, the triple for a
directory is generated before the triples for any of its subdirectories
(directories are generated top down). If topdown is false, the triple
for a directory is generated after the triples for all of its
subdirectories (directories are generated bottom up).
When topdown is true, the caller can modify the dirnames list in-place
(e.g., via del or slice assignment), and walk will only recurse into the
subdirectories whose names remain in dirnames; this can be used to prune the
search, or to impose a specific order of visiting. Modifying dirnames when
topdown is false is ineffective, since the directories in dirnames have
already been generated by the time dirnames itself is generated. No matter
the value of topdown, the list of subdirectories is retrieved before the
tuples for the directory and its subdirectories are generated.
By default errors from the os.scandir() call are ignored. If
optional arg 'onerror' is specified, it should be a function; it
will be called with one argument, an OSError instance. It can
report the error to continue with the walk, or raise the exception
to abort the walk. Note that the filename is available as the
filename attribute of the exception object.
By default, os.walk does not follow symbolic links to subdirectories on
systems that support them. In order to get this functionality, set the
optional argument 'followlinks' to true.
Caution: if you pass a relative pathname for top, don't change the
current working directory between resumptions of walk. walk never
changes the current directory, and assumes that the client doesn't
either.
Example:
import os
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
print(root, "consumes", end="")
print(sum([getsize(join(root, name)) for name in files]), end="")
print("bytes in", len(files), "non-directory files")
if 'CVS' in dirs:
dirs.remove('CVS') # don't visit CVS directories
"""
top=fspath(top)
dirs= []
nondirs= []
walk_dirs= []
# We may not have read permission for top, in which case we can't
# get a list of the files the directory contains. os.walk
# always suppressed the exception then, rather than blow up for a
# minor reason when (say) a thousand readable directories are still
# left to visit. That logic is copied here.
try:
# Note that scandir is global in this module due
# to earlier import-*.
scandir_it=scandir(top)
exceptOSErroraserror:
ifonerrorisnotNone:
onerror(error)
return
withscandir_it:
whileTrue:
try:
try:
entry=next(scandir_it)
exceptStopIteration:
break
exceptOSErroraserror:
ifonerrorisnotNone:
onerror(error)
return
try:
is_dir=entry.is_dir()
exceptOSError:
# If is_dir() raises an OSError, consider that the entry is not
# a directory, same behaviour than os.path.isdir().
is_dir=False
ifis_dir:
dirs.append(entry.name)
else:
nondirs.append(entry.name)
ifnottopdownandis_dir:
# Bottom-up: recurse into sub-directory, but exclude symlinks to
# directories if followlinks is False
iffollowlinks:
walk_into=True
else:
try:
is_symlink=entry.is_symlink()
exceptOSError:
# If is_symlink() raises an OSError, consider that the
# entry is not a symbolic link, same behaviour than
# os.path.islink().
is_symlink=False
walk_into=notis_symlink
ifwalk_into:
walk_dirs.append(entry.path)
# Yield before recursion if going top down
iftopdown:
yieldtop, dirs, nondirs
# Recurse into sub-directories
islink, join=path.islink, path.join
fordirnameindirs:
new_path=join(top, dirname)
# Issue #23605: os.path.islink() is used instead of caching
# entry.is_symlink() result during the loop on os.scandir() because
# the caller can replace the directory entry during the "yield"
# above.
iffollowlinksornotislink(new_path):
yieldfromwalk(new_path, topdown, onerror, followlinks)
else:
# Recurse into sub-directories
fornew_pathinwalk_dirs:
yieldfromwalk(new_path, topdown, onerror, followlinks)
# Yield after recursion if going bottom up
yieldtop, dirs, nondirs
__all__.append("walk")
if {open, stat} <=supports_dir_fdand {listdir, stat} <=supports_fd:
deffwalk(top=".", topdown=True, onerror=None, *, follow_symlinks=False, dir_fd=None):
"""Directory tree generator.
This behaves exactly like walk(), except that it yields a 4-tuple
dirpath, dirnames, filenames, dirfd
`dirpath`, `dirnames` and `filenames` are identical to walk() output,
and `dirfd` is a file descriptor referring to the directory `dirpath`.
The advantage of fwalk() over walk() is that it's safe against symlink
races (when follow_symlinks is False).
If dir_fd is not None, it should be a file descriptor open to a directory,
and top should be relative; top will then be relative to that directory.
(dir_fd is always supported for fwalk.)
Caution:
Since fwalk() yields file descriptors, those are only valid until the
next iteration step, so you should dup() them if you want to keep them
for a longer period.
Example:
import os
for root, dirs, files, rootfd in os.fwalk('python/Lib/email'):
print(root, "consumes", end="")
print(sum([os.stat(name, dir_fd=rootfd).st_size for name in files]),
end="")
print("bytes in", len(files), "non-directory files")
if 'CVS' in dirs:
dirs.remove('CVS') # don't visit CVS directories
"""
ifnotisinstance(top, int) ornothasattr(top, '__index__'):
top=fspath(top)
# Note: To guard against symlink races, we use the standard
# lstat()/open()/fstat() trick.
orig_st=stat(top, follow_symlinks=False, dir_fd=dir_fd)
topfd=open(top, O_RDONLY, dir_fd=dir_fd)
try:
if (follow_symlinksor (st.S_ISDIR(orig_st.st_mode) and
path.samestat(orig_st, stat(topfd)))):
yieldfrom_fwalk(topfd, top, topdown, onerror, follow_symlinks)
finally:
close(topfd)
def_fwalk(topfd, toppath, topdown, onerror, follow_symlinks):
# Note: This uses O(depth of the directory tree) file descriptors: if
# necessary, it can be adapted to only require O(1) FDs, see issue
# #13734.
names=listdir(topfd)
dirs, nondirs= [], []
fornameinnames:
try:
# Here, we don't use AT_SYMLINK_NOFOLLOW to be consistent with
# walk() which reports symlinks to directories as directories.
# We do however check for symlinks before recursing into
# a subdirectory.
ifst.S_ISDIR(stat(name, dir_fd=topfd).st_mode):
dirs.append(name)
else:
nondirs.append(name)
exceptOSError:
try:
# Add dangling symlinks, ignore disappeared files
ifst.S_ISLNK(stat(name, dir_fd=topfd, follow_symlinks=False)
.st_mode):
nondirs.append(name)
exceptOSError:
continue
iftopdown:
yieldtoppath, dirs, nondirs, topfd
fornameindirs:
try:
orig_st=stat(name, dir_fd=topfd, follow_symlinks=follow_symlinks)
dirfd=open(name, O_RDONLY, dir_fd=topfd)
exceptOSErroraserr:
ifonerrorisnotNone:
onerror(err)
continue
try:
iffollow_symlinksorpath.samestat(orig_st, stat(dirfd)):
dirpath=path.join(toppath, name)
yieldfrom_fwalk(dirfd, dirpath, topdown, onerror, follow_symlinks)
finally:
close(dirfd)
ifnottopdown:
yieldtoppath, dirs, nondirs, topfd
__all__.append("fwalk")
# Make sure os.environ exists, at least
try:
environ
exceptNameError:
environ= {}
defexecl(file, *args):
"""execl(file, *args)
Execute the executable file with argument list args, replacing the
current process. """
execv(file, args)
defexecle(file, *args):
"""execle(file, *args, env)
Execute the executable file with argument list args and
environment env, replacing the current process. """
env=args[-1]
execve(file, args[:-1], env)
defexeclp(file, *args):
"""execlp(file, *args)
Execute the executable file (which is searched for along $PATH)
with argument list args, replacing the current process. """
execvp(file, args)
defexeclpe(file, *args):
"""execlpe(file, *args, env)
Execute the executable file (which is searched for along $PATH)
with argument list args and environment env, replacing the current
process. """
env=args[-1]
execvpe(file, args[:-1], env)
defexecvp(file, args):
"""execvp(file, args)
Execute the executable file (which is searched for along $PATH)
with argument list args, replacing the current process.
args may be a list or tuple of strings. """
_execvpe(file, args)
defexecvpe(file, args, env):
"""execvpe(file, args, env)
Execute the executable file (which is searched for along $PATH)
with argument list args and environment env , replacing the
current process.
args may be a list or tuple of strings. """
_execvpe(file, args, env)
__all__.extend(["execl","execle","execlp","execlpe","execvp","execvpe"])
def_execvpe(file, args, env=None):
ifenvisnotNone:
exec_func=execve
argrest= (args, env)
else:
exec_func=execv
argrest= (args,)
env=environ
head, tail=path.split(file)
ifhead:
exec_func(file, *argrest)
return
last_exc=saved_exc=None
saved_tb=None
path_list=get_exec_path(env)
ifname!='nt':
file=fsencode(file)
path_list=map(fsencode, path_list)
fordirinpath_list:
fullname=path.join(dir, file)
try:
exec_func(fullname, *argrest)
exceptOSErrorase:
last_exc=e
tb=sys.exc_info()[2]
if (e.errno!=errno.ENOENTande.errno!=errno.ENOTDIR
andsaved_excisNone):
saved_exc=e
saved_tb=tb
ifsaved_exc:
raisesaved_exc.with_traceback(saved_tb)
raiselast_exc.with_traceback(tb)
defget_exec_path(env=None):
"""Returns the sequence of directories that will be searched for the
named executable (similar to a shell) when launching a process.
*env* must be an environment variable dict or None. If *env* is None,
os.environ will be used.
"""
# Use a local import instead of a global import to limit the number of
# modules loaded at startup: the os module is always loaded at startup by
# Python. It may also avoid a bootstrap issue.
importwarnings
ifenvisNone:
env=environ
# {b'PATH': ...}.get('PATH') and {'PATH': ...}.get(b'PATH') emit a
# BytesWarning when using python -b or python -bb: ignore the warning
withwarnings.catch_warnings():
warnings.simplefilter("ignore", BytesWarning)
try:
path_list=env.get('PATH')
exceptTypeError:
path_list=None
ifsupports_bytes_environ:
try:
path_listb=env[b'PATH']
except (KeyError, TypeError):
pass
else:
ifpath_listisnotNone:
raiseValueError(
"env cannot contain 'PATH' and b'PATH' keys")
path_list=path_listb
ifpath_listisnotNoneandisinstance(path_list, bytes):
path_list=fsdecode(path_list)
ifpath_listisNone:
path_list=defpath
returnpath_list.split(pathsep)
# Change environ to automatically call putenv(), unsetenv if they exist.
from_collections_abcimportMutableMapping
class_Environ(MutableMapping):
def__init__(self, data, encodekey, decodekey, encodevalue, decodevalue, putenv, unsetenv):
self.encodekey=encodekey
self.decodekey=decodekey
self.encodevalue=encodevalue
self.decodevalue=decodevalue
self.putenv=putenv
self.unsetenv=unsetenv
self._data=data
def__getitem__(self, key):
try:
value=self._data[self.encodekey(key)]
exceptKeyError:
# raise KeyError with the original key value
raiseKeyError(key) fromNone
returnself.decodevalue(value)
def__setitem__(self, key, value):
key=self.encodekey(key)
value=self.encodevalue(value)
self.putenv(key, value)
self._data[key] =value
def__delitem__(self, key):
encodedkey=self.encodekey(key)
self.unsetenv(encodedkey)
try:
delself._data[encodedkey]
exceptKeyError:
# raise KeyError with the original key value
raiseKeyError(key) fromNone
def__iter__(self):
# list() from dict object is an atomic operation
keys=list(self._data)
forkeyinkeys:
yieldself.decodekey(key)
def__len__(self):
returnlen(self._data)
def__repr__(self):
return'environ({{{}}})'.format(', '.join(
('{!r}: {!r}'.format(self.decodekey(key), self.decodevalue(value))
forkey, valueinself._data.items())))
defcopy(self):
returndict(self)
defsetdefault(self, key, value):
ifkeynotinself:
self[key] =value
returnself[key]
try:
_putenv=putenv
exceptNameError:
_putenv=lambdakey, value: None
else:
if"putenv"notin__all__:
__all__.append("putenv")
try:
_unsetenv=unsetenv
exceptNameError:
_unsetenv=lambdakey: _putenv(key, "")
else:
if"unsetenv"notin__all__:
__all__.append("unsetenv")
def_createenviron():
ifname=='nt':
# Where Env Var Names Must Be UPPERCASE
defcheck_str(value):
ifnotisinstance(value, str):
raiseTypeError("str expected, not %s"%type(value).__name__)
returnvalue
encode=check_str
decode=str
defencodekey(key):
returnencode(key).upper()
data= {}
forkey, valueinenviron.items():
data[encodekey(key)] =value
else:
# Where Env Var Names Can Be Mixed Case
encoding=sys.getfilesystemencoding()
defencode(value):
ifnotisinstance(value, str):
raiseTypeError("str expected, not %s"%type(value).__name__)
returnvalue.encode(encoding, 'surrogateescape')
defdecode(value):
returnvalue.decode(encoding, 'surrogateescape')
encodekey=encode
data=environ
return_Environ(data,
encodekey, decode,
encode, decode,
_putenv, _unsetenv)
# unicode environ
environ=_createenviron()
del_createenviron
defgetenv(key, default=None):
"""Get an environment variable, return None if it doesn't exist.
The optional second argument can specify an alternate default.
key, default and the result are str."""
returnenviron.get(key, default)
supports_bytes_environ= (name!='nt')
__all__.extend(("getenv", "supports_bytes_environ"))
ifsupports_bytes_environ:
def_check_bytes(value):
ifnotisinstance(value, bytes):
raiseTypeError("bytes expected, not %s"%type(value).__name__)
returnvalue
# bytes environ
environb=_Environ(environ._data,
_check_bytes, bytes,
_check_bytes, bytes,
_putenv, _unsetenv)
del_check_bytes
defgetenvb(key, default=None):
"""Get an environment variable, return None if it doesn't exist.
The optional second argument can specify an alternate default.
key, default and the result are bytes."""
returnenvironb.get(key, default)
__all__.extend(("environb", "getenvb"))
def_fscodec():
encoding=sys.getfilesystemencoding()
errors=sys.getfilesystemencodeerrors()
deffsencode(filename):
"""Encode filename (an os.PathLike, bytes, or str) to the filesystem
encoding with 'surrogateescape' error handler, return bytes unchanged.
On Windows, use 'strict' error handler if the file system encoding is
'mbcs' (which is the default encoding).
"""
filename=fspath(filename) # Does type-checking of `filename`.
ifisinstance(filename, str):
returnfilename.encode(encoding, errors)
else:
returnfilename
deffsdecode(filename):
"""Decode filename (an os.PathLike, bytes, or str) from the filesystem
encoding with 'surrogateescape' error handler, return str unchanged. On
Windows, use 'strict' error handler if the file system encoding is
'mbcs' (which is the default encoding).
"""
filename=fspath(filename) # Does type-checking of `filename`.
ifisinstance(filename, bytes):
returnfilename.decode(encoding, errors)
else:
returnfilename
returnfsencode, fsdecode
fsencode, fsdecode=_fscodec()
del_fscodec
# Supply spawn*() (probably only for Unix)
if_exists("fork") andnot_exists("spawnv") and_exists("execv"):
P_WAIT=0
P_NOWAIT=P_NOWAITO=1
__all__.extend(["P_WAIT", "P_NOWAIT", "P_NOWAITO"])
# XXX Should we support P_DETACH? I suppose it could fork()**2
# and close the std I/O streams. Also, P_OVERLAY is the same
# as execv*()?
def_spawnvef(mode, file, args, env, func):
# Internal helper; func is the exec*() function to use
ifnotisinstance(args, (tuple, list)):
raiseTypeError('argv must be a tuple or a list')
ifnotargsornotargs[0]:
raiseValueError('argv first element cannot be empty')
pid=fork()
ifnotpid:
# Child
try:
ifenvisNone:
func(file, args)
else:
func(file, args, env)
except:
_exit(127)
else:
# Parent
ifmode==P_NOWAIT:
returnpid# Caller is responsible for waiting!
while1:
wpid, sts=waitpid(pid, 0)
ifWIFSTOPPED(sts):
continue
elifWIFSIGNALED(sts):
return-WTERMSIG(sts)
elifWIFEXITED(sts):
returnWEXITSTATUS(sts)
else:
raiseOSError("Not stopped, signaled or exited???")
defspawnv(mode, file, args):
"""spawnv(mode, file, args) -> integer
Execute file with arguments from args in a subprocess.
If mode == P_NOWAIT return the pid of the process.
If mode == P_WAIT return the process's exit code if it exits normally;
otherwise return -SIG, where SIG is the signal that killed it. """
return_spawnvef(mode, file, args, None, execv)
defspawnve(mode, file, args, env):
"""spawnve(mode, file, args, env) -> integer
Execute file with arguments from args in a subprocess with the
specified environment.
If mode == P_NOWAIT return the pid of the process.
If mode == P_WAIT return the process's exit code if it exits normally;
otherwise return -SIG, where SIG is the signal that killed it. """
return_spawnvef(mode, file, args, env, execve)
# Note: spawnvp[e] isn't currently supported on Windows
defspawnvp(mode, file, args):
"""spawnvp(mode, file, args) -> integer
Execute file (which is looked for along $PATH) with arguments from
args in a subprocess.
If mode == P_NOWAIT return the pid of the process.
If mode == P_WAIT return the process's exit code if it exits normally;
otherwise return -SIG, where SIG is the signal that killed it. """
return_spawnvef(mode, file, args, None, execvp)
defspawnvpe(mode, file, args, env):
"""spawnvpe(mode, file, args, env) -> integer
Execute file (which is looked for along $PATH) with arguments from
args in a subprocess with the supplied environment.
If mode == P_NOWAIT return the pid of the process.
If mode == P_WAIT return the process's exit code if it exits normally;
otherwise return -SIG, where SIG is the signal that killed it. """
return_spawnvef(mode, file, args, env, execvpe)
__all__.extend(["spawnv", "spawnve", "spawnvp", "spawnvpe"])
if_exists("spawnv"):
# These aren't supplied by the basic Windows code
# but can be easily implemented in Python
defspawnl(mode, file, *args):
"""spawnl(mode, file, *args) -> integer
Execute file with arguments from args in a subprocess.
If mode == P_NOWAIT return the pid of the process.
If mode == P_WAIT return the process's exit code if it exits normally;
otherwise return -SIG, where SIG is the signal that killed it. """
returnspawnv(mode, file, args)
defspawnle(mode, file, *args):
"""spawnle(mode, file, *args, env) -> integer
Execute file with arguments from args in a subprocess with the
supplied environment.
If mode == P_NOWAIT return the pid of the process.
If mode == P_WAIT return the process's exit code if it exits normally;
otherwise return -SIG, where SIG is the signal that killed it. """
env=args[-1]
returnspawnve(mode, file, args[:-1], env)
__all__.extend(["spawnl", "spawnle"])
if_exists("spawnvp"):
# At the moment, Windows doesn't implement spawnvp[e],
# so it won't have spawnlp[e] either.
defspawnlp(mode, file, *args):
"""spawnlp(mode, file, *args) -> integer
Execute file (which is looked for along $PATH) with arguments from
args in a subprocess with the supplied environment.
If mode == P_NOWAIT return the pid of the process.
If mode == P_WAIT return the process's exit code if it exits normally;
otherwise return -SIG, where SIG is the signal that killed it. """
returnspawnvp(mode, file, args)
defspawnlpe(mode, file, *args):
"""spawnlpe(mode, file, *args, env) -> integer
Execute file (which is looked for along $PATH) with arguments from
args in a subprocess with the supplied environment.
If mode == P_NOWAIT return the pid of the process.
If mode == P_WAIT return the process's exit code if it exits normally;
otherwise return -SIG, where SIG is the signal that killed it. """
env=args[-1]
returnspawnvpe(mode, file, args[:-1], env)
__all__.extend(["spawnlp", "spawnlpe"])
# Supply os.popen()
defpopen(cmd, mode="r", buffering=-1):
ifnotisinstance(cmd, str):
raiseTypeError("invalid cmd type (%s, expected string)"%type(cmd))
ifmodenotin ("r", "w"):
raiseValueError("invalid mode %r"%mode)
ifbuffering==0orbufferingisNone:
raiseValueError("popen() does not support unbuffered streams")
importsubprocess, io
ifmode=="r":
proc=subprocess.Popen(cmd,
shell=True,
stdout=subprocess.PIPE,
bufsize=buffering)
return_wrap_close(io.TextIOWrapper(proc.stdout), proc)
else:
proc=subprocess.Popen(cmd,
shell=True,
stdin=subprocess.PIPE,
bufsize=buffering)
return_wrap_close(io.TextIOWrapper(proc.stdin), proc)
# Helper for popen() -- a proxy for a file whose close waits for the process
class_wrap_close:
def__init__(self, stream, proc):
self._stream=stream
self._proc=proc
defclose(self):
self._stream.close()
returncode=self._proc.wait()
ifreturncode==0:
returnNone
ifname=='nt':
returnreturncode