-
-
Notifications
You must be signed in to change notification settings - Fork 30.6k
/
os.rst
5805 lines (3771 loc) · 200 KB
/
os.rst
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
:mod:`!os` --- Miscellaneous operating system interfaces
========================================================
.. module:: os
:synopsis: Miscellaneous operating system interfaces.
**Source code:** :source:`Lib/os.py`
--------------
This module provides a portable way of using operating system dependent
functionality. If you just want to read or write a file see :func:`open`, if
you want to manipulate paths, see the :mod:`os.path` module, and if you want to
read all the lines in all the files on the command line see the :mod:`fileinput`
module. For creating temporary files and directories see the :mod:`tempfile`
module, and for high-level file and directory handling see the :mod:`shutil`
module.
Notes on the availability of these functions:
* The design of all built-in operating system dependent modules of Python is
such that as long as the same functionality is available, it uses the same
interface; for example, the function ``os.stat(path)`` returns stat
information about *path* in the same format (which happens to have originated
with the POSIX interface).
* Extensions peculiar to a particular operating system are also available
through the :mod:`os` module, but using them is of course a threat to
portability.
* All functions accepting path or file names accept both bytes and string
objects, and result in an object of the same type, if a path or file name is
returned.
* On VxWorks, os.popen, os.fork, os.execv and os.spawn*p* are not supported.
* On WebAssembly platforms, Android and iOS, large parts of the :mod:`os` module are
not available or behave differently. APIs related to processes (e.g.
:func:`~os.fork`, :func:`~os.execve`) and resources (e.g. :func:`~os.nice`)
are not available. Others like :func:`~os.getuid` and :func:`~os.getpid` are
emulated or stubs. WebAssembly platforms also lack support for signals (e.g.
:func:`~os.kill`, :func:`~os.wait`).
.. note::
All functions in this module raise :exc:`OSError` (or subclasses thereof) in
the case of invalid or inaccessible file names and paths, or other arguments
that have the correct type, but are not accepted by the operating system.
.. exception:: error
An alias for the built-in :exc:`OSError` exception.
.. data:: name
The name of the operating system dependent module imported. The following
names have currently been registered: ``'posix'``, ``'nt'``,
``'java'``.
.. seealso::
:data:`sys.platform` has a finer granularity. :func:`os.uname` gives
system-dependent version information.
The :mod:`platform` module provides detailed checks for the
system's identity.
.. _os-filenames:
.. _filesystem-encoding:
File Names, Command Line Arguments, and Environment Variables
-------------------------------------------------------------
In Python, file names, command line arguments, and environment variables are
represented using the string type. On some systems, decoding these strings to
and from bytes is necessary before passing them to the operating system. Python
uses the :term:`filesystem encoding and error handler` to perform this
conversion (see :func:`sys.getfilesystemencoding`).
The :term:`filesystem encoding and error handler` are configured at Python
startup by the :c:func:`PyConfig_Read` function: see
:c:member:`~PyConfig.filesystem_encoding` and
:c:member:`~PyConfig.filesystem_errors` members of :c:type:`PyConfig`.
.. versionchanged:: 3.1
On some systems, conversion using the file system encoding may fail. In this
case, Python uses the :ref:`surrogateescape encoding error handler
<surrogateescape>`, which means that undecodable bytes are replaced by a
Unicode character U+DC\ *xx* on decoding, and these are again
translated to the original byte on encoding.
The :term:`file system encoding <filesystem encoding and error handler>` must
guarantee to successfully decode all bytes below 128. If the file system
encoding fails to provide this guarantee, API functions can raise
:exc:`UnicodeError`.
See also the :term:`locale encoding`.
.. _utf8-mode:
Python UTF-8 Mode
-----------------
.. versionadded:: 3.7
See :pep:`540` for more details.
The Python UTF-8 Mode ignores the :term:`locale encoding` and forces the usage
of the UTF-8 encoding:
* Use UTF-8 as the :term:`filesystem encoding <filesystem encoding and error
handler>`.
* :func:`sys.getfilesystemencoding` returns ``'utf-8'``.
* :func:`locale.getpreferredencoding` returns ``'utf-8'`` (the *do_setlocale*
argument has no effect).
* :data:`sys.stdin`, :data:`sys.stdout`, and :data:`sys.stderr` all use
UTF-8 as their text encoding, with the ``surrogateescape``
:ref:`error handler <error-handlers>` being enabled for :data:`sys.stdin`
and :data:`sys.stdout` (:data:`sys.stderr` continues to use
``backslashreplace`` as it does in the default locale-aware mode)
* On Unix, :func:`os.device_encoding` returns ``'utf-8'`` rather than the
device encoding.
Note that the standard stream settings in UTF-8 mode can be overridden by
:envvar:`PYTHONIOENCODING` (just as they can be in the default locale-aware
mode).
As a consequence of the changes in those lower level APIs, other higher
level APIs also exhibit different default behaviours:
* Command line arguments, environment variables and filenames are decoded
to text using the UTF-8 encoding.
* :func:`os.fsdecode` and :func:`os.fsencode` use the UTF-8 encoding.
* :func:`open`, :func:`io.open`, and :func:`codecs.open` use the UTF-8
encoding by default. However, they still use the strict error handler by
default so that attempting to open a binary file in text mode is likely
to raise an exception rather than producing nonsense data.
The :ref:`Python UTF-8 Mode <utf8-mode>` is enabled if the LC_CTYPE locale is
``C`` or ``POSIX`` at Python startup (see the :c:func:`PyConfig_Read`
function).
It can be enabled or disabled using the :option:`-X utf8 <-X>` command line
option and the :envvar:`PYTHONUTF8` environment variable.
If the :envvar:`PYTHONUTF8` environment variable is not set at all, then the
interpreter defaults to using the current locale settings, *unless* the current
locale is identified as a legacy ASCII-based locale (as described for
:envvar:`PYTHONCOERCECLOCALE`), and locale coercion is either disabled or
fails. In such legacy locales, the interpreter will default to enabling UTF-8
mode unless explicitly instructed not to do so.
The Python UTF-8 Mode can only be enabled at the Python startup. Its value
can be read from :data:`sys.flags.utf8_mode <sys.flags>`.
See also the :ref:`UTF-8 mode on Windows <win-utf8-mode>`
and the :term:`filesystem encoding and error handler`.
.. seealso::
:pep:`686`
Python 3.15 will make :ref:`utf8-mode` default.
.. _os-procinfo:
Process Parameters
------------------
These functions and data items provide information and operate on the current
process and user.
.. function:: ctermid()
Return the filename corresponding to the controlling terminal of the process.
.. availability:: Unix, not WASI.
.. data:: environ
A :term:`mapping` object where keys and values are strings that represent
the process environment. For example, ``environ['HOME']`` is the pathname
of your home directory (on some platforms), and is equivalent to
``getenv("HOME")`` in C.
This mapping is captured the first time the :mod:`os` module is imported,
typically during Python startup as part of processing :file:`site.py`. Changes
to the environment made after this time are not reflected in :data:`os.environ`,
except for changes made by modifying :data:`os.environ` directly.
This mapping may be used to modify the environment as well as query the
environment. :func:`putenv` will be called automatically when the mapping
is modified.
On Unix, keys and values use :func:`sys.getfilesystemencoding` and
``'surrogateescape'`` error handler. Use :data:`environb` if you would like
to use a different encoding.
On Windows, the keys are converted to uppercase. This also applies when
getting, setting, or deleting an item. For example,
``environ['monty'] = 'python'`` maps the key ``'MONTY'`` to the value
``'python'``.
.. note::
Calling :func:`putenv` directly does not change :data:`os.environ`, so it's better
to modify :data:`os.environ`.
.. note::
On some platforms, including FreeBSD and macOS, setting ``environ`` may
cause memory leaks. Refer to the system documentation for
:c:func:`!putenv`.
You can delete items in this mapping to unset environment variables.
:func:`unsetenv` will be called automatically when an item is deleted from
:data:`os.environ`, and when one of the :meth:`pop` or :meth:`clear` methods is
called.
.. seealso::
The :func:`os.reload_environ` function.
.. versionchanged:: 3.9
Updated to support :pep:`584`'s merge (``|``) and update (``|=``) operators.
.. data:: environb
Bytes version of :data:`environ`: a :term:`mapping` object where both keys
and values are :class:`bytes` objects representing the process environment.
:data:`environ` and :data:`environb` are synchronized (modifying
:data:`environb` updates :data:`environ`, and vice versa).
:data:`environb` is only available if :const:`supports_bytes_environ` is
``True``.
.. versionadded:: 3.2
.. versionchanged:: 3.9
Updated to support :pep:`584`'s merge (``|``) and update (``|=``) operators.
.. function:: reload_environ()
The :data:`os.environ` and :data:`os.environb` mappings are a cache of
environment variables at the time that Python started.
As such, changes to the current process environment are not reflected
if made outside Python, or by :func:`os.putenv` or :func:`os.unsetenv`.
Use :func:`!os.reload_environ` to update :data:`os.environ` and :data:`os.environb`
with any such changes to the current process environment.
.. warning::
This function is not thread-safe. Calling it while the environment is
being modified in an other thread is an undefined behavior. Reading from
:data:`os.environ` or :data:`os.environb`, or calling :func:`os.getenv`
while reloading, may return an empty result.
.. versionadded:: next
.. function:: chdir(path)
fchdir(fd)
getcwd()
:noindex:
These functions are described in :ref:`os-file-dir`.
.. function:: fsencode(filename)
Encode :term:`path-like <path-like object>` *filename* to the
:term:`filesystem encoding and error handler`; return :class:`bytes`
unchanged.
:func:`fsdecode` is the reverse function.
.. versionadded:: 3.2
.. versionchanged:: 3.6
Support added to accept objects implementing the :class:`os.PathLike`
interface.
.. function:: fsdecode(filename)
Decode the :term:`path-like <path-like object>` *filename* from the
:term:`filesystem encoding and error handler`; return :class:`str`
unchanged.
:func:`fsencode` is the reverse function.
.. versionadded:: 3.2
.. versionchanged:: 3.6
Support added to accept objects implementing the :class:`os.PathLike`
interface.
.. function:: fspath(path)
Return the file system representation of the path.
If :class:`str` or :class:`bytes` is passed in, it is returned unchanged.
Otherwise :meth:`~os.PathLike.__fspath__` is called and its value is
returned as long as it is a :class:`str` or :class:`bytes` object.
In all other cases, :exc:`TypeError` is raised.
.. versionadded:: 3.6
.. class:: PathLike
An :term:`abstract base class` for objects representing a file system path,
e.g. :class:`pathlib.PurePath`.
.. versionadded:: 3.6
.. abstractmethod:: __fspath__()
Return the file system path representation of the object.
The method should only return a :class:`str` or :class:`bytes` object,
with the preference being for :class:`str`.
.. function:: getenv(key, default=None)
Return the value of the environment variable *key* as a string if it exists, or
*default* if it doesn't. *key* is a string. Note that
since :func:`getenv` uses :data:`os.environ`, the mapping of :func:`getenv` is
similarly also captured on import, and the function may not reflect
future environment changes.
On Unix, keys and values are decoded with :func:`sys.getfilesystemencoding`
and ``'surrogateescape'`` error handler. Use :func:`os.getenvb` if you
would like to use a different encoding.
.. availability:: Unix, Windows.
.. function:: getenvb(key, default=None)
Return the value of the environment variable *key* as bytes if it exists, or
*default* if it doesn't. *key* must be bytes. Note that
since :func:`getenvb` uses :data:`os.environb`, the mapping of :func:`getenvb` is
similarly also captured on import, and the function may not reflect
future environment changes.
:func:`getenvb` is only available if :const:`supports_bytes_environ`
is ``True``.
.. availability:: Unix.
.. versionadded:: 3.2
.. function:: get_exec_path(env=None)
Returns the list of directories that will be searched for a named
executable, similar to a shell, when launching a process.
*env*, when specified, should be an environment variable dictionary
to lookup the PATH in.
By default, when *env* is ``None``, :data:`environ` is used.
.. versionadded:: 3.2
.. function:: getegid()
Return the effective group id of the current process. This corresponds to the
"set id" bit on the file being executed in the current process.
.. availability:: Unix, not WASI.
.. function:: geteuid()
.. index:: single: user; effective id
Return the current process's effective user id.
.. availability:: Unix, not WASI.
.. function:: getgid()
.. index:: single: process; group
Return the real group id of the current process.
.. availability:: Unix.
The function is a stub on WASI, see :ref:`wasm-availability` for more
information.
.. function:: getgrouplist(user, group, /)
Return list of group ids that *user* belongs to. If *group* is not in the
list, it is included; typically, *group* is specified as the group ID
field from the password record for *user*, because that group ID will
otherwise be potentially omitted.
.. availability:: Unix, not WASI.
.. versionadded:: 3.3
.. function:: getgroups()
Return list of supplemental group ids associated with the current process.
.. availability:: Unix, not WASI.
.. note::
On macOS, :func:`getgroups` behavior differs somewhat from
other Unix platforms. If the Python interpreter was built with a
deployment target of ``10.5`` or earlier, :func:`getgroups` returns
the list of effective group ids associated with the current user process;
this list is limited to a system-defined number of entries, typically 16,
and may be modified by calls to :func:`setgroups` if suitably privileged.
If built with a deployment target greater than ``10.5``,
:func:`getgroups` returns the current group access list for the user
associated with the effective user id of the process; the group access
list may change over the lifetime of the process, it is not affected by
calls to :func:`setgroups`, and its length is not limited to 16. The
deployment target value, :const:`MACOSX_DEPLOYMENT_TARGET`, can be
obtained with :func:`sysconfig.get_config_var`.
.. function:: getlogin()
Return the name of the user logged in on the controlling terminal of the
process. For most purposes, it is more useful to use
:func:`getpass.getuser` since the latter checks the environment variables
:envvar:`LOGNAME` or :envvar:`USERNAME` to find out who the user is, and
falls back to ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the
current real user id.
.. availability:: Unix, Windows, not WASI.
.. function:: getpgid(pid)
Return the process group id of the process with process id *pid*. If *pid* is 0,
the process group id of the current process is returned.
.. availability:: Unix, not WASI.
.. function:: getpgrp()
.. index:: single: process; group
Return the id of the current process group.
.. availability:: Unix, not WASI.
.. function:: getpid()
.. index:: single: process; id
Return the current process id.
The function is a stub on WASI, see :ref:`wasm-availability` for more
information.
.. function:: getppid()
.. index:: single: process; id of parent
Return the parent's process id. When the parent process has exited, on Unix
the id returned is the one of the init process (1), on Windows it is still
the same id, which may be already reused by another process.
.. availability:: Unix, Windows, not WASI.
.. versionchanged:: 3.2
Added support for Windows.
.. function:: getpriority(which, who)
.. index:: single: process; scheduling priority
Get program scheduling priority. The value *which* is one of
:const:`PRIO_PROCESS`, :const:`PRIO_PGRP`, or :const:`PRIO_USER`, and *who*
is interpreted relative to *which* (a process identifier for
:const:`PRIO_PROCESS`, process group identifier for :const:`PRIO_PGRP`, and a
user ID for :const:`PRIO_USER`). A zero value for *who* denotes
(respectively) the calling process, the process group of the calling process,
or the real user ID of the calling process.
.. availability:: Unix, not WASI.
.. versionadded:: 3.3
.. data:: PRIO_PROCESS
PRIO_PGRP
PRIO_USER
Parameters for the :func:`getpriority` and :func:`setpriority` functions.
.. availability:: Unix, not WASI.
.. versionadded:: 3.3
.. data:: PRIO_DARWIN_THREAD
PRIO_DARWIN_PROCESS
PRIO_DARWIN_BG
PRIO_DARWIN_NONUI
Parameters for the :func:`getpriority` and :func:`setpriority` functions.
.. availability:: macOS
.. versionadded:: 3.12
.. function:: getresuid()
Return a tuple (ruid, euid, suid) denoting the current process's
real, effective, and saved user ids.
.. availability:: Unix, not WASI.
.. versionadded:: 3.2
.. function:: getresgid()
Return a tuple (rgid, egid, sgid) denoting the current process's
real, effective, and saved group ids.
.. availability:: Unix, not WASI.
.. versionadded:: 3.2
.. function:: getuid()
.. index:: single: user; id
Return the current process's real user id.
.. availability:: Unix.
The function is a stub on WASI, see :ref:`wasm-availability` for more
information.
.. function:: initgroups(username, gid, /)
Call the system initgroups() to initialize the group access list with all of
the groups of which the specified username is a member, plus the specified
group id.
.. availability:: Unix, not WASI, not Android.
.. versionadded:: 3.2
.. function:: putenv(key, value, /)
.. index:: single: environment variables; setting
Set the environment variable named *key* to the string *value*. Such
changes to the environment affect subprocesses started with :func:`os.system`,
:func:`popen` or :func:`fork` and :func:`execv`.
Assignments to items in :data:`os.environ` are automatically translated into
corresponding calls to :func:`putenv`; however, calls to :func:`putenv`
don't update :data:`os.environ`, so it is actually preferable to assign to items
of :data:`os.environ`. This also applies to :func:`getenv` and :func:`getenvb`, which
respectively use :data:`os.environ` and :data:`os.environb` in their implementations.
See also the :func:`os.reload_environ` function.
.. note::
On some platforms, including FreeBSD and macOS, setting ``environ`` may
cause memory leaks. Refer to the system documentation for :c:func:`!putenv`.
.. audit-event:: os.putenv key,value os.putenv
.. versionchanged:: 3.9
The function is now always available.
.. function:: setegid(egid, /)
Set the current process's effective group id.
.. availability:: Unix, not WASI, not Android.
.. function:: seteuid(euid, /)
Set the current process's effective user id.
.. availability:: Unix, not WASI, not Android.
.. function:: setgid(gid, /)
Set the current process' group id.
.. availability:: Unix, not WASI, not Android.
.. function:: setgroups(groups, /)
Set the list of supplemental group ids associated with the current process to
*groups*. *groups* must be a sequence, and each element must be an integer
identifying a group. This operation is typically available only to the superuser.
.. availability:: Unix, not WASI.
.. note:: On macOS, the length of *groups* may not exceed the
system-defined maximum number of effective group ids, typically 16.
See the documentation for :func:`getgroups` for cases where it may not
return the same group list set by calling setgroups().
.. function:: setns(fd, nstype=0)
Reassociate the current thread with a Linux namespace.
See the :manpage:`setns(2)` and :manpage:`namespaces(7)` man pages for more
details.
If *fd* refers to a :file:`/proc/{pid}/ns/` link, ``setns()`` reassociates the
calling thread with the namespace associated with that link,
and *nstype* may be set to one of the
:ref:`CLONE_NEW* constants <os-unshare-clone-flags>`
to impose constraints on the operation
(``0`` means no constraints).
Since Linux 5.8, *fd* may refer to a PID file descriptor obtained from
:func:`~os.pidfd_open`. In this case, ``setns()`` reassociates the calling thread
into one or more of the same namespaces as the thread referred to by *fd*.
This is subject to any constraints imposed by *nstype*,
which is a bit mask combining one or more of the
:ref:`CLONE_NEW* constants <os-unshare-clone-flags>`,
e.g. ``setns(fd, os.CLONE_NEWUTS | os.CLONE_NEWPID)``.
The caller's memberships in unspecified namespaces are left unchanged.
*fd* can be any object with a :meth:`~io.IOBase.fileno` method, or a raw file descriptor.
This example reassociates the thread with the ``init`` process's network namespace::
fd = os.open("/proc/1/ns/net", os.O_RDONLY)
os.setns(fd, os.CLONE_NEWNET)
os.close(fd)
.. availability:: Linux >= 3.0 with glibc >= 2.14.
.. versionadded:: 3.12
.. seealso::
The :func:`~os.unshare` function.
.. function:: setpgrp()
Call the system call :c:func:`!setpgrp` or ``setpgrp(0, 0)`` depending on
which version is implemented (if any). See the Unix manual for the semantics.
.. availability:: Unix, not WASI.
.. function:: setpgid(pid, pgrp, /)
Call the system call :c:func:`!setpgid` to set the process group id of the
process with id *pid* to the process group with id *pgrp*. See the Unix manual
for the semantics.
.. availability:: Unix, not WASI.
.. function:: setpriority(which, who, priority)
.. index:: single: process; scheduling priority
Set program scheduling priority. The value *which* is one of
:const:`PRIO_PROCESS`, :const:`PRIO_PGRP`, or :const:`PRIO_USER`, and *who*
is interpreted relative to *which* (a process identifier for
:const:`PRIO_PROCESS`, process group identifier for :const:`PRIO_PGRP`, and a
user ID for :const:`PRIO_USER`). A zero value for *who* denotes
(respectively) the calling process, the process group of the calling process,
or the real user ID of the calling process.
*priority* is a value in the range -20 to 19. The default priority is 0;
lower priorities cause more favorable scheduling.
.. availability:: Unix, not WASI.
.. versionadded:: 3.3
.. function:: setregid(rgid, egid, /)
Set the current process's real and effective group ids.
.. availability:: Unix, not WASI, not Android.
.. function:: setresgid(rgid, egid, sgid, /)
Set the current process's real, effective, and saved group ids.
.. availability:: Unix, not WASI, not Android.
.. versionadded:: 3.2
.. function:: setresuid(ruid, euid, suid, /)
Set the current process's real, effective, and saved user ids.
.. availability:: Unix, not WASI, not Android.
.. versionadded:: 3.2
.. function:: setreuid(ruid, euid, /)
Set the current process's real and effective user ids.
.. availability:: Unix, not WASI, not Android.
.. function:: getsid(pid, /)
Call the system call :c:func:`!getsid`. See the Unix manual for the semantics.
.. availability:: Unix, not WASI.
.. function:: setsid()
Call the system call :c:func:`!setsid`. See the Unix manual for the semantics.
.. availability:: Unix, not WASI.
.. function:: setuid(uid, /)
.. index:: single: user; id, setting
Set the current process's user id.
.. availability:: Unix, not WASI, not Android.
.. placed in this section since it relates to errno.... a little weak
.. function:: strerror(code, /)
Return the error message corresponding to the error code in *code*.
On platforms where :c:func:`!strerror` returns ``NULL`` when given an unknown
error number, :exc:`ValueError` is raised.
.. data:: supports_bytes_environ
``True`` if the native OS type of the environment is bytes (eg. ``False`` on
Windows).
.. versionadded:: 3.2
.. function:: umask(mask, /)
Set the current numeric umask and return the previous umask.
The function is a stub on WASI, see :ref:`wasm-availability` for more
information.
.. function:: uname()
.. index::
single: gethostname() (in module socket)
single: gethostbyaddr() (in module socket)
Returns information identifying the current operating system.
The return value is an object with five attributes:
* :attr:`sysname` - operating system name
* :attr:`nodename` - name of machine on network (implementation-defined)
* :attr:`release` - operating system release
* :attr:`version` - operating system version
* :attr:`machine` - hardware identifier
For backwards compatibility, this object is also iterable, behaving
like a five-tuple containing :attr:`sysname`, :attr:`nodename`,
:attr:`release`, :attr:`version`, and :attr:`machine`
in that order.
Some systems truncate :attr:`nodename` to 8 characters or to the
leading component; a better way to get the hostname is
:func:`socket.gethostname` or even
``socket.gethostbyaddr(socket.gethostname())``.
On macOS, iOS and Android, this returns the *kernel* name and version (i.e.,
``'Darwin'`` on macOS and iOS; ``'Linux'`` on Android). :func:`platform.uname`
can be used to get the user-facing operating system name and version on iOS and
Android.
.. availability:: Unix.
.. versionchanged:: 3.3
Return type changed from a tuple to a tuple-like object
with named attributes.
.. function:: unsetenv(key, /)
.. index:: single: environment variables; deleting
Unset (delete) the environment variable named *key*. Such changes to the
environment affect subprocesses started with :func:`os.system`, :func:`popen` or
:func:`fork` and :func:`execv`.
Deletion of items in :data:`os.environ` is automatically translated into a
corresponding call to :func:`unsetenv`; however, calls to :func:`unsetenv`
don't update :data:`os.environ`, so it is actually preferable to delete items of
:data:`os.environ`.
See also the :func:`os.reload_environ` function.
.. audit-event:: os.unsetenv key os.unsetenv
.. versionchanged:: 3.9
The function is now always available and is also available on Windows.
.. function:: unshare(flags)
Disassociate parts of the process execution context, and move them into a
newly created namespace.
See the :manpage:`unshare(2)`
man page for more details.
The *flags* argument is a bit mask, combining zero or more of the
:ref:`CLONE_* constants <os-unshare-clone-flags>`,
that specifies which parts of the execution context should be
unshared from their existing associations and moved to a new namespace.
If the *flags* argument is ``0``, no changes are made to the calling process's
execution context.
.. availability:: Linux >= 2.6.16.
.. versionadded:: 3.12
.. seealso::
The :func:`~os.setns` function.
.. _os-unshare-clone-flags:
Flags to the :func:`unshare` function, if the implementation supports them.
See :manpage:`unshare(2)` in the Linux manual
for their exact effect and availability.
.. data:: CLONE_FILES
CLONE_FS
CLONE_NEWCGROUP
CLONE_NEWIPC
CLONE_NEWNET
CLONE_NEWNS
CLONE_NEWPID
CLONE_NEWTIME
CLONE_NEWUSER
CLONE_NEWUTS
CLONE_SIGHAND
CLONE_SYSVSEM
CLONE_THREAD
CLONE_VM
.. _os-newstreams:
File Object Creation
--------------------
These functions create new :term:`file objects <file object>`. (See also
:func:`~os.open` for opening file descriptors.)
.. function:: fdopen(fd, *args, **kwargs)
Return an open file object connected to the file descriptor *fd*. This is an
alias of the :func:`open` built-in function and accepts the same arguments.
The only difference is that the first argument of :func:`fdopen` must always
be an integer.
.. _os-fd-ops:
File Descriptor Operations
--------------------------
These functions operate on I/O streams referenced using file descriptors.
File descriptors are small integers corresponding to a file that has been opened
by the current process. For example, standard input is usually file descriptor
0, standard output is 1, and standard error is 2. Further files opened by a
process will then be assigned 3, 4, 5, and so forth. The name "file descriptor"
is slightly deceptive; on Unix platforms, sockets and pipes are also referenced
by file descriptors.
The :meth:`~io.IOBase.fileno` method can be used to obtain the file descriptor
associated with a :term:`file object` when required. Note that using the file
descriptor directly will bypass the file object methods, ignoring aspects such
as internal buffering of data.
.. function:: close(fd)
Close file descriptor *fd*.
.. note::
This function is intended for low-level I/O and must be applied to a file
descriptor as returned by :func:`os.open` or :func:`pipe`. To close a "file
object" returned by the built-in function :func:`open` or by :func:`popen` or
:func:`fdopen`, use its :meth:`~io.IOBase.close` method.
.. function:: closerange(fd_low, fd_high, /)
Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive),
ignoring errors. Equivalent to (but much faster than)::
for fd in range(fd_low, fd_high):
try:
os.close(fd)
except OSError:
pass
.. function:: copy_file_range(src, dst, count, offset_src=None, offset_dst=None)
Copy *count* bytes from file descriptor *src*, starting from offset
*offset_src*, to file descriptor *dst*, starting from offset *offset_dst*.
If *offset_src* is ``None``, then *src* is read from the current position;
respectively for *offset_dst*.
In Linux kernel older than 5.3, the files pointed to by *src* and *dst*
must reside in the same filesystem, otherwise an :exc:`OSError` is
raised with :attr:`~OSError.errno` set to :const:`errno.EXDEV`.
This copy is done without the additional cost of transferring data
from the kernel to user space and then back into the kernel. Additionally,
some filesystems could implement extra optimizations, such as the use of
reflinks (i.e., two or more inodes that share pointers to the same
copy-on-write disk blocks; supported file systems include btrfs and XFS)
and server-side copy (in the case of NFS).
The function copies bytes between two file descriptors. Text options, like
the encoding and the line ending, are ignored.
The return value is the amount of bytes copied. This could be less than the
amount requested.
.. note::
On Linux, :func:`os.copy_file_range` should not be used for copying a
range of a pseudo file from a special filesystem like procfs and sysfs.
It will always copy no bytes and return 0 as if the file was empty
because of a known Linux kernel issue.
.. availability:: Linux >= 4.5 with glibc >= 2.27.
.. versionadded:: 3.8
.. function:: device_encoding(fd)
Return a string describing the encoding of the device associated with *fd*
if it is connected to a terminal; else return :const:`None`.
On Unix, if the :ref:`Python UTF-8 Mode <utf8-mode>` is enabled, return
``'UTF-8'`` rather than the device encoding.
.. versionchanged:: 3.10
On Unix, the function now implements the Python UTF-8 Mode.
.. function:: dup(fd, /)
Return a duplicate of file descriptor *fd*. The new file descriptor is
:ref:`non-inheritable <fd_inheritance>`.