FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[Original HTTPS Page]
cpython/Lib/platform.py at 3.15 · python/cpython · GitHub
python
cpython
Repository navigation
Code
Issues
5k+
(5k+)
Pull requests
2.7k
(2.7k)
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
cpython
/
Lib
/
platform.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
1446 lines (1175 loc) · 45.6 KB
Breadcrumbs
cpython
/
Lib
/
platform.py
Copy path
File metadata and controls
1446 lines (1175 loc) · 45.6 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
""" This module tries to retrieve as much platform-identifying data as
possible. It makes this information available via function APIs.
If called from the command line, it prints the platform
information concatenated as single string to stdout. The output
format is usable as part of a filename.
"""
# This module is maintained by Marc-Andre Lemburg <mal@egenix.com>.
# If you find problems, please submit bug reports/patches via the
# Python issue tracker (https://github.com/python/cpython/issues) and
# mention "@malemburg".
#
# Still needed:
# * support for MS-DOS (PythonDX ?)
# * support for Amiga and other still unsupported platforms running Python
# * support for additional Linux distributions
#
# Many thanks to all those who helped adding platform-specific
# checks (in no particular order):
#
# Charles G Waldman, David Arnold, Gordon McMillan, Ben Darnell,
# Jeff Bauer, Cliff Crawford, Ivan Van Laningham, Josef
# Betancourt, Randall Hopper, Karl Putland, John Farrell, Greg
# Andruk, Just van Rossum, Thomas Heller, Mark R. Levinson, Mark
# Hammond, Bill Tutt, Hans Nowak, Uwe Zessin (OpenVMS support),
# Colin Kong, Trent Mick, Guido van Rossum, Anthony Baxter, Steve
# Dower
#
# History:
#
# <see checkin messages for history>
#
# 1.0.9 - added invalidate_caches() function to invalidate cached values
# 1.0.8 - changed Windows support to read version from kernel32.dll
# 1.0.7 - added DEV_NULL
# 1.0.6 - added linux_distribution()
# 1.0.5 - fixed Java support to allow running the module on Jython
# 1.0.4 - added IronPython support
# 1.0.3 - added normalization of Windows system name
# 1.0.2 - added more Windows support
# 1.0.1 - reformatted to make doc.py happy
# 1.0.0 - reformatted a bit and checked into Python CVS
# 0.8.0 - added sys.version parser and various new access
# APIs (python_version(), python_compiler(), etc.)
# 0.7.2 - fixed architecture() to use sizeof(pointer) where available
# 0.7.1 - added support for Caldera OpenLinux
# 0.7.0 - some fixes for WinCE; untabified the source file
# 0.6.2 - support for OpenVMS - requires version 1.5.2-V006 or higher and
# vms_lib.getsyi() configured
# 0.6.1 - added code to prevent 'uname -p' on platforms which are
# known not to support it
# 0.6.0 - fixed win32_ver() to hopefully work on Win95,98,NT and Win2k;
# did some cleanup of the interfaces - some APIs have changed
# 0.5.5 - fixed another type in the MacOS code... should have
# used more coffee today ;-)
# 0.5.4 - fixed a few typos in the MacOS code
# 0.5.3 - added experimental MacOS support; added better popen()
# workarounds in _syscmd_ver() -- still not 100% elegant
# though
# 0.5.2 - fixed uname() to return '' instead of 'unknown' in all
# return values (the system uname command tends to return
# 'unknown' instead of just leaving the field empty)
# 0.5.1 - included code for slackware dist; added exception handlers
# to cover up situations where platforms don't have os.popen
# (e.g. Mac) or fail on socket.gethostname(); fixed libc
# detection RE
# 0.5.0 - changed the API names referring to system commands to *syscmd*;
# added java_ver(); made syscmd_ver() a private
# API (was system_ver() in previous versions) -- use uname()
# instead; extended the win32_ver() to also return processor
# type information
# 0.4.0 - added win32_ver() and modified the platform() output for WinXX
# 0.3.4 - fixed a bug in _follow_symlinks()
# 0.3.3 - fixed popen() and "file" command invocation bugs
# 0.3.2 - added architecture() API and support for it in platform()
# 0.3.1 - fixed syscmd_ver() RE to support Windows NT
# 0.3.0 - added system alias support
# 0.2.3 - removed 'wince' again... oh well.
# 0.2.2 - added 'wince' to syscmd_ver() supported platforms
# 0.2.1 - added cache logic and changed the platform string format
# 0.2.0 - changed the API to use functions instead of module globals
# since some action take too long to be run on module import
# 0.1.0 - first release
#
# You can always get the latest version of this module at:
#
# http://www.egenix.com/files/python/platform.py
#
# If that URL should fail, try contacting the author.
__copyright__
=
"""
Copyright (c) 1999-2000, Marc-Andre Lemburg; mailto:mal@lemburg.com
Copyright (c) 2000-2010, eGenix.com Software GmbH; mailto:info@egenix.com
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee or royalty is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation or portions thereof, including modifications,
that you make.
EGENIX.COM SOFTWARE GMBH DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
WITH THE USE OR PERFORMANCE OF THIS SOFTWARE !
"""
import
collections
import
os
import
re
import
sys
import
functools
import
itertools
try
:
import
_wmi
except
ImportError
:
_wmi
=
None
### Globals & Constants
# Helper for comparing two version number strings.
# Based on the description of the PHP's version_compare():
# http://php.net/manual/en/function.version-compare.php
_ver_stages
=
frozendict
({
# any string not found in this dict, will get 0 assigned
'dev'
:
10
,
'alpha'
:
20
,
'a'
:
20
,
'beta'
:
30
,
'b'
:
30
,
'c'
:
40
,
'RC'
:
50
,
'rc'
:
50
,
# number, will get 100 assigned
'pl'
:
200
,
'p'
:
200
,
})
def
_comparable_version
(
version
):
component_re
=
re
.
compile
(
r'([0-9]+|[._+-])'
)
result
=
[]
for
v
in
component_re
.
split
(
version
):
if
v
not
in
'._+-'
:
try
:
v
=
int
(
v
,
10
)
t
=
100
except
ValueError
:
t
=
_ver_stages
.
get
(
v
,
0
)
result
.
extend
((
t
,
v
))
return
result
### Platform specific APIs
def
libc_ver
(
executable
=
None
,
lib
=
''
,
version
=
''
,
chunksize
=
16384
):
""" Tries to determine the libc version that the file executable
(which defaults to the Python interpreter) is linked against.
Returns a tuple of strings (lib,version) which default to the
given parameters in case the lookup fails.
Note that the function has intimate knowledge of how different
libc versions add symbols to the executable and thus is probably
only usable for executables compiled using gcc.
The file is read and scanned in chunks of chunksize bytes.
"""
if
not
executable
:
if
sys
.
platform
==
"emscripten"
:
# Emscripten's os.confstr reports that it is glibc, so special case
# it.
ver
=
"."
.
join
(
str
(
x
)
for
x
in
sys
.
_emscripten_info
.
emscripten_version
)
return
(
"emscripten"
,
ver
)
try
:
ver
=
os
.
confstr
(
'CS_GNU_LIBC_VERSION'
)
# parse 'glibc 2.28' as ('glibc', '2.28')
parts
=
ver
.
split
(
maxsplit
=
1
)
if
len
(
parts
)
==
2
:
return
tuple
(
parts
)
except
(
AttributeError
,
ValueError
,
OSError
):
# os.confstr() or CS_GNU_LIBC_VERSION value not available
pass
executable
=
sys
.
executable
if
not
executable
:
# sys.executable is not set.
return
lib
,
version
libc_search
=
re
.
compile
(
br"""
(__libc_init)
| (GLIBC_([0-9.]+))
| (libc(_\w+)?\.so(?:\.(\d[0-9.]*))?)
| (musl-([0-9.]+))
| ((?:libc\.|ld-)musl(?:-\w+)?.so(?:\.(\d[0-9.]*))?)
"""
,
re
.
ASCII
|
re
.
VERBOSE
)
V
=
_comparable_version
# We use os.path.realpath()
# here to work around problems with Cygwin not being
# able to open symlinks for reading
executable
=
os
.
path
.
realpath
(
executable
)
ver
=
None
with
open
(
executable
,
'rb'
)
as
f
:
binary
=
f
.
read
(
chunksize
)
pos
=
0
while
pos
<
len
(
binary
):
if
b'libc'
in
binary
or
b'GLIBC'
in
binary
or
b'musl'
in
binary
:
m
=
libc_search
.
search
(
binary
,
pos
)
else
:
m
=
None
if
not
m
or
m
.
end
()
==
len
(
binary
):
chunk
=
f
.
read
(
chunksize
)
if
chunk
:
binary
=
binary
[
max
(
pos
,
len
(
binary
)
-
1000
):]
+
chunk
pos
=
0
continue
if
not
m
:
break
decoded_groups
=
[
s
.
decode
(
'latin1'
)
if
s
is
not
None
else
s
for
s
in
m
.
groups
()]
(
libcinit
,
glibc
,
glibcversion
,
so
,
threads
,
soversion
,
musl
,
muslversion
,
musl_so
,
musl_sover
)
=
decoded_groups
if
libcinit
and
not
lib
:
lib
=
'libc'
elif
glibc
:
if
lib
!=
'glibc'
:
lib
=
'glibc'
ver
=
glibcversion
elif
V
(
glibcversion
)
>
V
(
ver
):
ver
=
glibcversion
elif
so
:
if
lib
not
in
(
'glibc'
,
'musl'
):
lib
=
'libc'
if
soversion
and
(
not
ver
or
V
(
soversion
)
>
V
(
ver
)):
ver
=
soversion
if
threads
and
ver
[
-
len
(
threads
):]
!=
threads
:
ver
=
ver
+
threads
elif
musl
:
lib
=
'musl'
if
not
ver
or
V
(
muslversion
)
>
V
(
ver
):
ver
=
muslversion
elif
musl_so
:
lib
=
'musl'
if
musl_sover
and
(
not
ver
or
V
(
musl_sover
)
>
V
(
ver
)):
ver
=
musl_sover
pos
=
m
.
end
()
return
lib
,
version
if
ver
is
None
else
ver
def
_norm_version
(
version
,
build
=
''
):
""" Normalize the version and build strings and return a single
version string using the format major.minor.build (or patchlevel).
"""
l
=
version
.
split
(
'.'
)
if
build
:
l
.
append
(
build
)
try
:
strings
=
list
(
map
(
str
,
map
(
int
,
l
)))
except
ValueError
:
strings
=
l
version
=
'.'
.
join
(
strings
[:
3
])
return
version
# Examples of VER command output:
#
# Windows 2000: Microsoft Windows 2000 [Version 5.00.2195]
# Windows XP: Microsoft Windows XP [Version 5.1.2600]
# Windows Vista: Microsoft Windows [Version 6.0.6002]
#
# Note that the "Version" string gets localized on different
# Windows versions.
def
_syscmd_ver
(
system
=
''
,
release
=
''
,
version
=
''
,
supported_platforms
=
(
'win32'
,
'win16'
,
'dos'
)):
""" Tries to figure out the OS version used and returns
a tuple (system, release, version).
It uses the "ver" shell command for this which is known
to exists on Windows, DOS. XXX Others too ?
In case this fails, the given parameters are used as
defaults.
"""
if
sys
.
platform
not
in
supported_platforms
:
return
system
,
release
,
version
# Try some common cmd strings
import
subprocess
for
cmd
in
(
'ver'
,
'command /c ver'
,
'cmd /c ver'
):
try
:
info
=
subprocess
.
check_output
(
cmd
,
stdin
=
subprocess
.
DEVNULL
,
stderr
=
subprocess
.
DEVNULL
,
text
=
True
,
encoding
=
"locale"
,
shell
=
True
)
except
(
OSError
,
subprocess
.
CalledProcessError
):
continue
else
:
break
else
:
return
system
,
release
,
version
ver_output
=
re
.
compile
(
r'(?:([\w ]+) ([\w.]+) '
r'.*'
r'\[.* ([\d.]+)\])'
)
# Parse the output
info
=
info
.
strip
()
m
=
ver_output
.
match
(
info
)
if
m
is
not
None
:
system
,
release
,
version
=
m
.
groups
()
# Strip trailing dots from version and release
if
release
[
-
1
]
==
'.'
:
release
=
release
[:
-
1
]
if
version
[
-
1
]
==
'.'
:
version
=
version
[:
-
1
]
# Normalize the version and build strings (eliminating additional
# zeros)
version
=
_norm_version
(
version
)
return
system
,
release
,
version
def
_wmi_query
(
table
,
*
keys
):
global
_wmi
if
not
_wmi
:
raise
OSError
(
"not supported"
)
table
=
{
"OS"
:
"Win32_OperatingSystem"
,
"CPU"
:
"Win32_Processor"
,
}[
table
]
try
:
data
=
_wmi
.
exec_query
(
"SELECT {} FROM {}"
.
format
(
","
.
join
(
keys
),
table
,
)).
split
(
"
\0
"
)
except
OSError
:
_wmi
=
None
raise
OSError
(
"not supported"
)
split_data
=
(
i
.
partition
(
"="
)
for
i
in
data
)
dict_data
=
{
i
[
0
]:
i
[
2
]
for
i
in
split_data
}
return
(
dict_data
[
k
]
for
k
in
keys
)
_WIN32_CLIENT_RELEASES
=
[
((
10
,
1
,
0
),
"post11"
),
((
10
,
0
,
22000
),
"11"
),
((
6
,
4
,
0
),
"10"
),
((
6
,
3
,
0
),
"8.1"
),
((
6
,
2
,
0
),
"8"
),
((
6
,
1
,
0
),
"7"
),
((
6
,
0
,
0
),
"Vista"
),
((
5
,
2
,
3790
),
"XP64"
),
((
5
,
2
,
0
),
"XPMedia"
),
((
5
,
1
,
0
),
"XP"
),
((
5
,
0
,
0
),
"2000"
),
]
_WIN32_SERVER_RELEASES
=
[
((
10
,
1
,
0
),
"post2025Server"
),
((
10
,
0
,
26100
),
"2025Server"
),
((
10
,
0
,
20348
),
"2022Server"
),
((
10
,
0
,
17763
),
"2019Server"
),
((
6
,
4
,
0
),
"2016Server"
),
((
6
,
3
,
0
),
"2012ServerR2"
),
((
6
,
2
,
0
),
"2012Server"
),
((
6
,
1
,
0
),
"2008ServerR2"
),
((
6
,
0
,
0
),
"2008Server"
),
((
5
,
2
,
0
),
"2003Server"
),
((
5
,
0
,
0
),
"2000Server"
),
]
def
win32_is_iot
():
return
win32_edition
()
in
(
'IoTUAP'
,
'NanoServer'
,
'WindowsCoreHeadless'
,
'IoTEdgeOS'
)
def
win32_edition
():
try
:
import
winreg
except
ImportError
:
pass
else
:
try
:
cvkey
=
r'SOFTWARE\Microsoft\Windows NT\CurrentVersion'
with
winreg
.
OpenKeyEx
(
winreg
.
HKEY_LOCAL_MACHINE
,
cvkey
)
as
key
:
return
winreg
.
QueryValueEx
(
key
,
'EditionId'
)[
0
]
except
OSError
:
pass
return
None
def
_win32_ver
(
version
,
csd
,
ptype
):
# Try using WMI first, as this is the canonical source of data
try
:
(
version
,
product_type
,
ptype
,
spmajor
,
spminor
)
=
_wmi_query
(
'OS'
,
'Version'
,
'ProductType'
,
'BuildType'
,
'ServicePackMajorVersion'
,
'ServicePackMinorVersion'
,
)
is_client
=
(
int
(
product_type
)
==
1
)
if
spminor
and
spminor
!=
'0'
:
csd
=
f'SP
{
spmajor
}
.
{
spminor
}
'
else
:
csd
=
f'SP
{
spmajor
}
'
return
version
,
csd
,
ptype
,
is_client
except
OSError
:
pass
# Fall back to a combination of sys.getwindowsversion and "ver"
try
:
from
sys
import
getwindowsversion
except
ImportError
:
return
version
,
csd
,
ptype
,
True
winver
=
getwindowsversion
()
is_client
=
(
getattr
(
winver
,
'product_type'
,
1
)
==
1
)
try
:
version
=
_syscmd_ver
()[
2
]
major
,
minor
,
build
=
map
(
int
,
version
.
split
(
'.'
))
except
ValueError
:
major
,
minor
,
build
=
winver
.
platform_version
or
winver
[:
3
]
version
=
'{0}.{1}.{2}'
.
format
(
major
,
minor
,
build
)
# getwindowsversion() reflect the compatibility mode Python is
# running under, and so the service pack value is only going to be
# valid if the versions match.
if
winver
[:
2
]
==
(
major
,
minor
):
try
:
csd
=
'SP{}'
.
format
(
winver
.
service_pack_major
)
except
AttributeError
:
if
csd
[:
13
]
==
'Service Pack '
:
csd
=
'SP'
+
csd
[
13
:]
try
:
import
winreg
except
ImportError
:
pass
else
:
try
:
cvkey
=
r'SOFTWARE\Microsoft\Windows NT\CurrentVersion'
with
winreg
.
OpenKeyEx
(
winreg
.
HKEY_LOCAL_MACHINE
,
cvkey
)
as
key
:
ptype
=
winreg
.
QueryValueEx
(
key
,
'CurrentType'
)[
0
]
except
OSError
:
pass
return
version
,
csd
,
ptype
,
is_client
def
win32_ver
(
release
=
''
,
version
=
''
,
csd
=
''
,
ptype
=
''
):
is_client
=
False
version
,
csd
,
ptype
,
is_client
=
_win32_ver
(
version
,
csd
,
ptype
)
if
version
:
intversion
=
tuple
(
map
(
int
,
version
.
split
(
'.'
)))
releases
=
_WIN32_CLIENT_RELEASES
if
is_client
else
_WIN32_SERVER_RELEASES
release
=
next
((
r
for
v
,
r
in
releases
if
v
<=
intversion
),
release
)
return
release
,
version
,
csd
,
ptype
def
_mac_ver_xml
():
fn
=
'/System/Library/CoreServices/SystemVersion.plist'
if
not
os
.
path
.
exists
(
fn
):
return
None
try
:
import
plistlib
except
ImportError
:
return
None
with
open
(
fn
,
'rb'
)
as
f
:
pl
=
plistlib
.
load
(
f
)
release
=
pl
[
'ProductVersion'
]
versioninfo
=
(
''
,
''
,
''
)
machine
=
os
.
uname
().
machine
if
machine
in
(
'ppc'
,
'Power Macintosh'
):
# Canonical name
machine
=
'PowerPC'
return
release
,
versioninfo
,
machine
def
mac_ver
(
release
=
''
,
versioninfo
=
(
''
,
''
,
''
),
machine
=
''
):
""" Get macOS version information and return it as tuple (release,
versioninfo, machine) with versioninfo being a tuple (version,
dev_stage, non_release_version).
Entries which cannot be determined are set to the parameter values
which default to ''. All tuple entries are strings.
"""
# First try reading the information from an XML file which should
# always be present
info
=
_mac_ver_xml
()
if
info
is
not
None
:
return
info
# If that also doesn't work return the default values
return
release
,
versioninfo
,
machine
# A namedtuple for iOS version information.
IOSVersionInfo
=
collections
.
namedtuple
(
"IOSVersionInfo"
,
[
"system"
,
"release"
,
"model"
,
"is_simulator"
]
)
def
ios_ver
(
system
=
""
,
release
=
""
,
model
=
""
,
is_simulator
=
False
):
"""Get iOS version information, and return it as a namedtuple:
(system, release, model, is_simulator).
If values can't be determined, they are set to values provided as
parameters.
"""
if
sys
.
platform
==
"ios"
:
import
_ios_support
result
=
_ios_support
.
get_platform_ios
()
if
result
is
not
None
:
return
IOSVersionInfo
(
*
result
)
return
IOSVersionInfo
(
system
,
release
,
model
,
is_simulator
)
AndroidVer
=
collections
.
namedtuple
(
"AndroidVer"
,
"release api_level manufacturer model device is_emulator"
)
def
android_ver
(
release
=
""
,
api_level
=
0
,
manufacturer
=
""
,
model
=
""
,
device
=
""
,
is_emulator
=
False
):
if
sys
.
platform
==
"android"
:
try
:
from
ctypes
import
CDLL
,
c_char_p
,
create_string_buffer
except
ImportError
:
pass
else
:
# An NDK developer confirmed that this is an officially-supported
# API (https://stackoverflow.com/a/28416743). Use `getattr` to avoid
# private name mangling.
system_property_get
=
getattr
(
CDLL
(
"libc.so"
),
"__system_property_get"
)
system_property_get
.
argtypes
=
(
c_char_p
,
c_char_p
)
def
getprop
(
name
,
default
):
# https://android.googlesource.com/platform/bionic/+/refs/tags/android-5.0.0_r1/libc/include/sys/system_properties.h#39
PROP_VALUE_MAX
=
92
buffer
=
create_string_buffer
(
PROP_VALUE_MAX
)
length
=
system_property_get
(
name
.
encode
(
"UTF-8"
),
buffer
)
if
length
==
0
:
# This API doesn’t distinguish between an empty property and
# a missing one.
return
default
else
:
return
buffer
.
value
.
decode
(
"UTF-8"
,
"backslashreplace"
)
release
=
getprop
(
"ro.build.version.release"
,
release
)
api_level
=
int
(
getprop
(
"ro.build.version.sdk"
,
api_level
))
manufacturer
=
getprop
(
"ro.product.manufacturer"
,
manufacturer
)
model
=
getprop
(
"ro.product.model"
,
model
)
device
=
getprop
(
"ro.product.device"
,
device
)
is_emulator
=
getprop
(
"ro.kernel.qemu"
,
"0"
)
==
"1"
return
AndroidVer
(
release
,
api_level
,
manufacturer
,
model
,
device
,
is_emulator
)
### System name aliasing
def
system_alias
(
system
,
release
,
version
):
""" Returns (system, release, version) aliased to common
marketing names used for some systems.
It also does some reordering of the information in some cases
where it would otherwise cause confusion.
"""
if
system
==
'SunOS'
:
# Sun's OS
if
release
<
'5'
:
# These releases use the old name SunOS
return
system
,
release
,
version
# Modify release (marketing release = SunOS release - 3)
l
=
release
.
split
(
'.'
)
if
l
:
try
:
major
=
int
(
l
[
0
])
except
ValueError
:
pass
else
:
major
=
major
-
3
l
[
0
]
=
str
(
major
)
release
=
'.'
.
join
(
l
)
if
release
<
'6'
:
system
=
'Solaris'
else
:
# XXX Whatever the new SunOS marketing name is...
system
=
'Solaris'
elif
system
in
(
'win32'
,
'win16'
):
# In case one of the other tricks
system
=
'Windows'
# bpo-35516: Don't replace Darwin with macOS since input release and
# version arguments can be different than the currently running version.
return
system
,
release
,
version
### Various internal helpers
# Table for cleaning up characters in filenames.
_SIMPLE_SUBSTITUTIONS
=
str
.
maketrans
(
r' /\:;"()'
,
r'_-------'
)
def
_platform
(
*
args
):
""" Helper to format the platform string in a filename
compatible format e.g. "system-version-machine".
"""
# Format the platform string
platform
=
'-'
.
join
(
x
.
strip
()
for
x
in
filter
(
len
,
args
))
# Cleanup some possible filename obstacles...
platform
=
platform
.
translate
(
_SIMPLE_SUBSTITUTIONS
)
# No need to report 'unknown' information...
platform
=
platform
.
replace
(
'unknown'
,
''
)
# Fold '--'s and remove trailing '-'
return
re
.
sub
(
r'-{2,}'
,
'-'
,
platform
).
rstrip
(
'-'
)
def
_node
(
default
=
''
):
""" Helper to determine the node name of this machine.
"""
try
:
import
socket
except
ImportError
:
# No sockets...
return
default
try
:
return
socket
.
gethostname
()
except
OSError
:
# Still not working...
return
default
def
_follow_symlinks
(
filepath
):
""" In case filepath is a symlink, follow it until a
real file is reached.
"""
filepath
=
os
.
path
.
abspath
(
filepath
)
while
os
.
path
.
islink
(
filepath
):
filepath
=
os
.
path
.
normpath
(
os
.
path
.
join
(
os
.
path
.
dirname
(
filepath
),
os
.
readlink
(
filepath
)))
return
filepath
def
_syscmd_file
(
target
,
default
=
''
):
""" Interface to the system's file command.
The function uses the -b option of the file command to have it
omit the filename in its output. Follow the symlinks. It returns
default in case the command should fail.
"""
if
sys
.
platform
in
{
'dos'
,
'win32'
,
'win16'
,
'ios'
,
'tvos'
,
'watchos'
}:
# XXX Others too ?
return
default
try
:
import
subprocess
except
ImportError
:
return
default
target
=
_follow_symlinks
(
target
)
# "file" output is locale dependent: force the usage of the C locale
# to get deterministic behavior.
env
=
dict
(
os
.
environ
,
LC_ALL
=
'C'
)
try
:
# -b: do not prepend filenames to output lines (brief mode)
output
=
subprocess
.
check_output
([
'file'
,
'-b'
,
target
],
stderr
=
subprocess
.
DEVNULL
,
env
=
env
)
except
(
OSError
,
subprocess
.
CalledProcessError
):
return
default
if
not
output
:
return
default
# With the C locale, the output should be mostly ASCII-compatible.
# Decode from Latin-1 to prevent Unicode decode error.
return
output
.
decode
(
'latin-1'
)
### Information about the used architecture
# Default values for architecture; non-empty strings override the
# defaults given as parameters
_default_architecture
=
frozendict
({
'win32'
: (
''
,
'WindowsPE'
),
'win16'
: (
''
,
'Windows'
),
'dos'
: (
''
,
'MSDOS'
),
})
def
architecture
(
executable
=
sys
.
executable
,
bits
=
''
,
linkage
=
''
):
""" Queries the given executable (defaults to the Python interpreter
binary) for various architecture information.
Returns a tuple (bits, linkage) which contains information about
the bit architecture and the linkage format used for the
executable. Both values are returned as strings.
Values that cannot be determined are returned as given by the
parameter presets. If bits is given as '', the sizeof(pointer)
(or sizeof(long) on Python version < 1.5.2) is used as
indicator for the supported pointer size.
The function relies on the system's "file" command to do the
actual work. This is available on most if not all Unix
platforms. On some non-Unix platforms where the "file" command
does not exist and the executable is set to the Python interpreter
binary defaults from _default_architecture are used.
"""
# Use the sizeof(pointer) as default number of bits if nothing
# else is given as default.
if
not
bits
:
import
struct
size
=
struct
.
calcsize
(
'P'
)
bits
=
str
(
size
*
8
)
+
'bit'
# Get data from the 'file' system command
if
executable
:
fileout
=
_syscmd_file
(
executable
,
''
)
else
:
fileout
=
''
if
not
fileout
and
\
executable
==
sys
.
executable
:
# "file" command did not return anything; we'll try to provide
# some sensible defaults then...
if
sys
.
platform
in
_default_architecture
:
b
,
l
=
_default_architecture
[
sys
.
platform
]
if
b
:
bits
=
b
if
l
:
linkage
=
l
return
bits
,
linkage
if
'executable'
not
in
fileout
and
'shared object'
not
in
fileout
:
# Format not supported
return
bits
,
linkage
# Bits
if
'32-bit'
in
fileout
:
bits
=
'32bit'
elif
'64-bit'
in
fileout
:
bits
=
'64bit'
# Linkage
if
'ELF'
in
fileout
:
linkage
=
'ELF'
elif
'Mach-O'
in
fileout
:
linkage
=
"Mach-O"
elif
'PE'
in
fileout
:
# E.g. Windows uses this format
if
'Windows'
in
fileout
:
linkage
=
'WindowsPE'
else
:
linkage
=
'PE'
elif
'COFF'
in
fileout
:
linkage
=
'COFF'
elif
'MS-DOS'
in
fileout
:
linkage
=
'MSDOS'
else
:
# XXX the A.OUT format also falls under this class...
pass
return
bits
,
linkage
def
_get_machine_win32
():
# Try to use the PROCESSOR_* environment variables
# available on Win XP and later; see
# http://support.microsoft.com/kb/888731 and
# http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM
# WOW64 processes mask the native architecture
try
:
[
arch
,
*
_
]
=
_wmi_query
(
'CPU'
,
'Architecture'
)
except
OSError
:
pass
else
:
try
:
arch
=
[
'x86'
,
'MIPS'
,
'Alpha'
,
'PowerPC'
,
None
,
'ARM'
,
'ia64'
,
None
,
None
,
'AMD64'
,
None
,
None
,
'ARM64'
,
][
int
(
arch
)]
except
(
ValueError
,
IndexError
):
pass
else
:
if
arch
:
return
arch
return
(
os
.
environ
.
get
(
'PROCESSOR_ARCHITEW6432'
,
''
)
or
os
.
environ
.
get
(
'PROCESSOR_ARCHITECTURE'
,
''
)
)
class
_Processor
:
@
classmethod
def
get
(
cls
):
func
=
getattr
(
cls
,
f'get_
{
sys
.
platform
}
'
,
cls
.
from_subprocess
)
return
func
()
or
''
def
get_win32
():
try
:
manufacturer
,
caption
=
_wmi_query
(
'CPU'
,
'Manufacturer'
,
'Caption'
)
except
OSError
:
return
os
.
environ
.
get
(
'PROCESSOR_IDENTIFIER'
,
_get_machine_win32
())
else
:
return
f'
{
caption
}
,
{
manufacturer
}
'
def
get_OpenVMS
():
try
:
import
vms_lib
except
ImportError
:
pass
else
:
csid
,
cpu_number
=
vms_lib
.
getsyi
(
'SYI$_CPU'
,
0
)
return
'Alpha'
if
cpu_number
>=
128
else
'VAX'
# On the iOS simulator, os.uname returns the architecture as uname.machine.
# On device it returns the model name for some reason; but there's only one
# CPU architecture for iOS devices, so we know the right answer.
def
get_ios
():
if
sys
.
implementation
.
_multiarch
.
endswith
(
"simulator"
):
return
os
.
uname
().
machine
return
'arm64'
def
from_subprocess
():
"""
Fall back to `uname -p`
"""
try
:
import
subprocess
except
ImportError
:
return
None
try
:
return
subprocess
.
check_output
(
[
'uname'
,
'-p'
],
stderr
=
subprocess
.
DEVNULL
,
text
=
True
,
encoding
=
"utf8"
,
).
strip
()
except
(
OSError
,
subprocess
.
CalledProcessError
):
pass
def
_unknown_as_blank
(
val
):
return
''
if
val
==
'unknown'
else
val
### Portable uname() interface
class
uname_result
(
collections
.
namedtuple
(
"uname_result_base"
,
"system node release version machine"
)
):
"""
A uname_result that's largely compatible with a
simple namedtuple except that 'processor' is
resolved late and cached to avoid calling "uname"
except when needed.
"""
_fields
=
(
'system'
,
'node'
,
'release'
,
'version'
,
'machine'
,
'processor'
)
@
functools
.
cached_property
def
processor
(
self
):
return
_unknown_as_blank
(
_Processor
.
get
())
def
__iter__
(
self
):
return
itertools
.
chain
(
super
().
__iter__
(),
(
self
.
processor
,)
)
@
classmethod
def
_make
(
cls
,
iterable
):
# override factory to affect length check
num_fields
=
len
(
cls
.
_fields
)
-
1
result
=
cls
.
__new__
(
cls
,
*
iterable
)
if
len
(
result
)
!=
num_fields
+
1
:
msg
=
f'Expected
{
num_fields
}
arguments, got
{
len
(
result
)
}
'
raise
TypeError
(
msg
)
return
result
def
__getitem__
(
self
,
key
):
return
tuple
(
self
)[
key
]
def
__len__
(
self
):
return
len
(
tuple
(
iter
(
self
)))
def
__reduce__
(
self
):
return
uname_result
,
tuple
(
self
)[:
len
(
self
.
_fields
)
-
1
]
_uname_cache
=
None
def
uname
():
""" Fairly portable uname interface. Returns a tuple
of strings (system, node, release, version, machine, processor)
identifying the underlying platform.
Note that unlike the os.uname function this also returns
possible processor information as an additional tuple entry.
Entries which cannot be determined are set to ''.
"""
global
_uname_cache
if
_uname_cache
is
not
None
:
return
_uname_cache
# Get some infos from the builtin os.uname API...
try
:
system
,
node
,
release
,
version
,
machine
=
infos
=
os
.
uname
()
except
AttributeError
:
system
=
sys
.
platform
node
=
_node
()
release
=
version
=
machine
=
''
infos
=
()
if
not
any
(
infos
):
# uname is not available
# Try win32_ver() on win32 platforms
if
system
==
'win32'
:
release
,
version
,
csd
,
ptype
=
win32_ver
()
machine
=
machine
or
_get_machine_win32
()
# Try the 'ver' system command available on some
# platforms
if
not
(
release
and
version
):
system
,
release
,
version
=
_syscmd_ver
(
system
)
# Normalize system to what win32_ver() normally returns
# (_syscmd_ver() tends to return the vendor name as well)
if
system
==
'Microsoft Windows'
:
system
=
'Windows'
elif
system
==
'Microsoft'
and
release
==
'Windows'
:
# Under Windows Vista and Windows Server 2008,
# Microsoft changed the output of the ver command. The
# release is no longer printed. This causes the
# system and release to be misidentified.
system
=
'Windows'
if
'6.0'
==
version
[:
3
]:
release
=
'Vista'
else
:
release
=
''
# In case we still don't know anything useful, we'll try to
# help ourselves
if
system
in
(
'win32'
,
'win16'
):
if
not
version
:
if
system
==
'win32'
:
version
=
'32bit'
else
:
version
=
'16bit'
system
=
'Windows'
# System specific extensions
if
system
==
'OpenVMS'
:
# OpenVMS seems to have release and version mixed up
if
not
release
or
release
==
'0'
:
release
=
version
version
=
''
# normalize name
if
system
==
'Microsoft'
and
release
==
'Windows'
:
system
=
'Windows'
release
=
'Vista'
# On Android, return the name and version of the OS rather than the kernel.
if
sys
.
platform
==
'android'
:
system
=
'Android'
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL