Python tạo tệp từ biến

Mô-đun này cung cấp một cách di động để sử dụng chức năng phụ thuộc vào hệ điều hành. Nếu bạn chỉ muốn đọc hoặc ghi một tệp, hãy xem, nếu bạn muốn thao tác với các đường dẫn, hãy xem mô-đun và nếu bạn muốn đọc tất cả các dòng trong tất cả các tệp trên dòng lệnh, hãy xem mô-đun. Để tạo các tệp và thư mục tạm thời, hãy xem mô-đun và để xử lý tệp và thư mục cấp cao, hãy xem mô-đun

Lưu ý về tính khả dụng của các chức năng này

  • Thiết kế của tất cả các mô-đun phụ thuộc hệ điều hành tích hợp sẵn của Python sao cho miễn là có cùng chức năng, thì nó sử dụng cùng một giao diện;

  • Các tiện ích mở rộng dành riêng cho một hệ điều hành cụ thể cũng có sẵn thông qua mô-đun, nhưng việc sử dụng chúng tất nhiên là một mối đe dọa đối với tính di động

  • Tất cả các hàm chấp nhận tên đường dẫn hoặc tệp đều chấp nhận cả byte và đối tượng chuỗi và dẫn đến một đối tượng cùng loại, nếu đường dẫn hoặc tên tệp được trả về

  • Trên VxWorks, hệ điều hành. giáo hoàng, os. ngã ba, hệ điều hành. execv và hệ điều hành. sinh sản * p * không được hỗ trợ

  • Trên nền tảng WebAssembly

    try:
        fp = open("myfile")
    except PermissionError:
        return "some default data"
    else:
        with fp:
            return fp.read()
    
    3 và
    try:
        fp = open("myfile")
    except PermissionError:
        return "some default data"
    else:
        with fp:
            return fp.read()
    
    4, phần lớn mô-đun không có sẵn hoặc hoạt động khác đi. API liên quan đến các quy trình (e. g. , ), tín hiệu (e. g. , ) và tài nguyên (e. g. ) không có sẵn. Những người khác thích và được mô phỏng hoặc sơ khai

Ghi chú

Tất cả các chức năng trong mô-đun này tăng (hoặc các lớp con của chúng) trong trường hợp tên và đường dẫn tệp không hợp lệ hoặc không thể truy cập được hoặc các đối số khác có loại chính xác nhưng không được hệ điều hành chấp nhận

ngoại lệ os. lỗi

Bí danh cho ngoại lệ tích hợp

os. name

Tên của mô-đun phụ thuộc hệ điều hành đã nhập. Những tên sau đây hiện đã được đăng ký.

with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)
5,
with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)
6,
with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)
7

See also

has a finer granularity. gives system-dependent version information

The module provides detailed checks for the system’s identity

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 to perform this conversion (see )

The are configured at Python startup by the

>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
st_mtime=1297230027, st_ctime=1297230027)
>>> statinfo.st_size
264
2 function. see and members of

Changed in version 3. 1. On some systems, conversion using the file system encoding may fail. In this case, Python uses the , which means that undecodable bytes are replaced by a Unicode character U+DCxx on decoding, and these are again translated to the original byte on encoding.

The must guarantee to successfully decode all bytes below 128. If the file system encoding fails to provide this guarantee, API functions can raise

See also the

Python UTF-8 Mode

New in version 3. 7. See PEP 540 for more details.

The Python UTF-8 Mode ignores the and forces the usage of the UTF-8 encoding

  • Use UTF-8 as the

  • trả về

    >>> import os
    >>> statinfo = os.stat('somefile.txt')
    >>> statinfo
    os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
    st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
    st_mtime=1297230027, st_ctime=1297230027)
    >>> statinfo.st_size
    264
    
    8

  • returns

    >>> import os
    >>> statinfo = os.stat('somefile.txt')
    >>> statinfo
    os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
    st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
    st_mtime=1297230027, st_ctime=1297230027)
    >>> statinfo.st_size
    264
    
    8 (the do_setlocale argument has no effect)

  • , , and all use UTF-8 as their text encoding, with the

    os.stat in os.supports_dir_fd
    
    4 being enabled for and ( continues to use
    os.stat in os.supports_dir_fd
    
    8 as it does in the default locale-aware mode)

  • On Unix, returns

    >>> import os
    >>> statinfo = os.stat('somefile.txt')
    >>> statinfo
    os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
    st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
    st_mtime=1297230027, st_ctime=1297230027)
    >>> statinfo.st_size
    264
    
    8 rather than the device encoding

Lưu ý rằng cài đặt luồng tiêu chuẩn ở chế độ UTF-8 có thể bị ghi đè bởi (giống như chúng có thể ở chế độ nhận biết ngôn ngữ mặc định)

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

  • and use the UTF-8 encoding

  • , , and 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 is enabled if the LC_CTYPE locale is

os.access in os.supports_effective_ids
7 or
os.access in os.supports_effective_ids
8 at Python startup (see the
>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
st_mtime=1297230027, st_ctime=1297230027)
>>> statinfo.st_size
264
2 function)

It can be enabled or disabled using the command line option and the environment variable

If the 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 ), 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

See also the and the

See also

PEP 686

Python 3. 15 will make default

Process Parameters

These functions and data items provide information and operate on the current process and user

os. ctermid()

Return the filename corresponding to the controlling terminal of the process

Unix, not Emscripten, not WASI

os. environ

A object where keys and values are strings that represent the process environment. For example,

os.chdir in os.supports_fd
5 is the pathname of your home directory (on some platforms), and is equivalent to
os.chdir in os.supports_fd
6 in C

This mapping is captured the first time the module is imported, typically during Python startup as part of processing

os.chdir in os.supports_fd
8. Changes to the environment made after this time are not reflected in , except for changes made by modifying directly

This mapping may be used to modify the environment as well as query the environment. will be called automatically when the mapping is modified

On Unix, keys and values use and

os.stat in os.supports_follow_symlinks
3 error handler. Use if you would like to use a different encoding

Ghi chú

Calling directly does not change , so it’s better to modify

Ghi chú

On some platforms, including FreeBSD and macOS, setting

os.stat in os.supports_follow_symlinks
8 may cause memory leaks. Refer to the system documentation for
os.stat in os.supports_follow_symlinks
1

You can delete items in this mapping to unset environment variables. will be called automatically when an item is deleted from , and when one of the

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
2 or
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
3 methods is called

Changed in version 3. 9. Updated to support PEP 584’s merge (

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
4) and update (
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
5) operators.

os. environb

Bytes version of . a object where both keys and values are objects representing the process environment. and are synchronized (modifying updates , and vice versa)

is only available if is

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04

Mới trong phiên bản 3. 2

Changed in version 3. 9. Updated to support PEP 584’s merge (

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
4) and update (
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
5) operators.

os. chdir(đường dẫn)os. fchdir(fd)os. getcwd()

Các chức năng này được mô tả trong

os. mã fsencode(tên tệp)

Mã hóa tên tệp thành ;

là hàm ngược

Mới trong phiên bản 3. 2

Đã thay đổi trong phiên bản 3. 6. Hỗ trợ được thêm vào để chấp nhận các đối tượng triển khai giao diện.

os. fsdecode(tên tệp)

Giải mã tên tệp từ ;

là hàm ngược

Mới trong phiên bản 3. 2

Đã thay đổi trong phiên bản 3. 6. Hỗ trợ được thêm vào để chấp nhận các đối tượng triển khai giao diện.

os. fspath(path)

Trả về biểu diễn hệ thống tệp của đường dẫn

If or is passed in, it is returned unchanged. Otherwise is called and its value is returned as long as it is a or object. In all other cases, is raised

New in version 3. 6

lớp os. Giống đường dẫn

An for objects representing a file system path, e. g.

New in version 3. 6

abstractmethod __fspath__()

Return the file system path representation of the object

The method should only return a or object, with the preference being for

os. 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 uses , the mapping of is similarly also captured on import, and the function may not reflect future environment changes

On Unix, keys and values are decoded with and

os.stat in os.supports_follow_symlinks
3 error handler. Use if you would like to use a different encoding

Unix, Windows

os. 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 uses , the mapping of is similarly also captured on import, and the function may not reflect future environment changes

is only available if is

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04

Unix

Mới trong phiên bản 3. 2

os. 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

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
35, is used

Mới trong phiên bản 3. 2

os. 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

Unix, not Emscripten, not WASI

os. geteuid()

Return the current process’s effective user id

Unix, not Emscripten, not WASI

os. getgid()

Return the real group id of the current process

Unix

The function is a stub on Emscripten and WASI, see for more information

os. 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

Unix, not Emscripten, not WASI

New in version 3. 3

os. getgroups()

Return list of supplemental group ids associated with the current process

Unix, not Emscripten, not WASI

Ghi chú

On macOS, behavior differs somewhat from other Unix platforms. If the Python interpreter was built with a deployment target of

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
38 or earlier, 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 if suitably privileged. If built with a deployment target greater than
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
38, 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 , and its length is not limited to 16. The deployment target value,
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
44, can be obtained with

os. 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 since the latter checks the environment variables

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
47 or
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
48 to find out who the user is, and falls back to
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
49 to get the login name of the current real user id

Unix, Windows, not Emscripten, not WASI

os. 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

Unix, not Emscripten, not WASI

os. getpgrp()

Return the id of the current process group

Unix, not Emscripten, not WASI

os. getpid()

Return the current process id

The function is a stub on Emscripten and WASI, see for more information

os. getppid()

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

Unix, Windows, not Emscripten, not WASI

Changed in version 3. 2. Added support for Windows.

os. getpriority(which , who)

Get program scheduling priority. The value which is one of , , or , and who is interpreted relative to which (a process identifier for , process group identifier for , and a user ID for ). 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

Unix, not Emscripten, not WASI

New in version 3. 3

os. PRIO_PROCESSos. PRIO_PGRPos. PRIO_USER

Parameters for the and functions

Unix, not Emscripten, not WASI

New in version 3. 3

os. getresuid()

Return a tuple (ruid, euid, suid) denoting the current process’s real, effective, and saved user ids

Unix, not Emscripten, not WASI

Mới trong phiên bản 3. 2

os. getresgid()

Return a tuple (rgid, egid, sgid) denoting the current process’s real, effective, and saved group ids

Unix, not Emscripten, not WASI

Mới trong phiên bản 3. 2

os. getuid()

Return the current process’s real user id

Unix

The function is a stub on Emscripten and WASI, see for more information

os. 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

Unix, not Emscripten, not WASI

Mới trong phiên bản 3. 2

os. putenv(key , value , /)

Set the environment variable named key to the string value. Such changes to the environment affect subprocesses started with , or and

Assignments to items in are automatically translated into corresponding calls to ; however, calls to don’t update , so it is actually preferable to assign to items of . This also applies to and , which respectively use and in their implementations

Ghi chú

On some platforms, including FreeBSD and macOS, setting

os.stat in os.supports_follow_symlinks
8 may cause memory leaks. Refer to the system documentation for
os.stat in os.supports_follow_symlinks
1

Raises an

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
73 with arguments
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
74,
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
75

Changed in version 3. 9. The function is now always available.

os. setegid(egid , /)

Set the current process’s effective group id

Unix, not Emscripten, not WASI

os. seteuid(euid , /)

Set the current process’s effective user id

Unix, not Emscripten, not WASI

os. setgid(gid , /)

Set the current process’ group id

Unix, not Emscripten, not WASI

os. 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

Unix, not Emscripten, not WASI

Ghi chú

On macOS, the length of groups may not exceed the system-defined maximum number of effective group ids, typically 16. See the documentation for for cases where it may not return the same group list set by calling setgroups()

os. setpgrp()

Call the system call

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
77 or
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
78 depending on which version is implemented (if any). See the Unix manual for the semantics

Unix, not Emscripten, not WASI

os. setpgid(pid , pgrp , /)

Call the system call

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
79 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

Unix, not Emscripten, not WASI

os. setpriority(which , who , priority)

Set program scheduling priority. The value which is one of , , or , and who is interpreted relative to which (a process identifier for , process group identifier for , and a user ID for ). 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

Unix, not Emscripten, not WASI

New in version 3. 3

os. setregid(rgid , egid , /)

Set the current process’s real and effective group ids

Unix, not Emscripten, not WASI

os. setresgid(rgid , egid , sgid , /)

Set the current process’s real, effective, and saved group ids

Unix, not Emscripten, not WASI

Mới trong phiên bản 3. 2

os. setresuid(ruid , euid , suid , /)

Đặt id người dùng thực, hiệu quả và đã lưu của quy trình hiện tại

Unix, not Emscripten, not WASI

Mới trong phiên bản 3. 2

os. setreuid(ruid , euid , /)

Set the current process’s real and effective user ids

Unix, not Emscripten, not WASI

os. getsid(pid , /)

Call the system call

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
86. See the Unix manual for the semantics

Unix, not Emscripten, not WASI

os. setsid()

Call the system call

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
87. See the Unix manual for the semantics

Unix, not Emscripten, not WASI

os. setuid(uid , /)

Set the current process’s user id

Unix, not Emscripten, not WASI

os. lỗi( , /)

Return the error message corresponding to the error code in code. On platforms where

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
88 returns
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
89 when given an unknown error number, is raised

os. supports_bytes_environ

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04 if the native OS type of the environment is bytes (eg.
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
92 on Windows)

Mới trong phiên bản 3. 2

os. umask(mask , /)

Set the current numeric umask and return the previous umask

The function is a stub on Emscripten and WASI, see for more information

os. uname()

Returns information identifying the current operating system. The return value is an object with five attributes

  • if os.access("myfile", os.R_OK):
        with open("myfile") as fp:
            return fp.read()
    return "some default data"
    
    93 - operating system name

  • if os.access("myfile", os.R_OK):
        with open("myfile") as fp:
            return fp.read()
    return "some default data"
    
    94 - name of machine on network (implementation-defined)

  • if os.access("myfile", os.R_OK):
        with open("myfile") as fp:
            return fp.read()
    return "some default data"
    
    95 - operating system release

  • if os.access("myfile", os.R_OK):
        with open("myfile") as fp:
            return fp.read()
    return "some default data"
    
    96 - operating system version

  • if os.access("myfile", os.R_OK):
        with open("myfile") as fp:
            return fp.read()
    return "some default data"
    
    97 - hardware identifier

For backwards compatibility, this object is also iterable, behaving like a five-tuple containing

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
93,
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
94,
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
95,
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
96, and
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
97 in that order

Some systems truncate

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
94 to 8 characters or to the leading component; a better way to get the hostname is or even
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
05

Unix

Changed in version 3. 3. Return type changed from a tuple to a tuple-like object with named attributes.

os. unsetenv(key , /)

Unset (delete) the environment variable named key. Such changes to the environment affect subprocesses started with , or and

Deletion of items in is automatically translated into a corresponding call to ; however, calls to don’t update , so it is actually preferable to delete items of

Raises an

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
15 with argument
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
74

Changed in version 3. 9. The function is now always available and is also available on Windows.

File Object Creation

These functions create new . (See also for opening file descriptors. )

os. fdopen(fd , *args , **kwargs)

Return an open file object connected to the file descriptor fd. This is an alias of the built-in function and accepts the same arguments. The only difference is that the first argument of must always be an integer

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 method can be used to obtain the file descriptor associated with a when required. Note that using the file descriptor directly will bypass the file object methods, ignoring aspects such as internal buffering of data

os. close(fd)

Close file descriptor fd

Ghi chú

This function is intended for low-level I/O and must be applied to a file descriptor as returned by or . To close a “file object” returned by the built-in function or by or , use its method

os. 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

os. 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. The files pointed by src and dst must reside in the same filesystem, otherwise an is raised with set to

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. The copy is done as if both files are opened as binary

The return value is the amount of bytes copied. This could be less than the amount requested

Linux >= 4. 5 with glibc >= 2. 27

New in version 3. 8

os. device_encoding(fd)

Return a string describing the encoding of the device associated with fd if it is connected to a terminal; else return

On Unix, if the is enabled, return

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
31 rather than the device encoding

Changed in version 3. 10. On Unix, the function now implements the Python UTF-8 Mode.

os. dup(fd , /)

Return a duplicate of file descriptor fd. Bộ mô tả tệp mới là

On Windows, when duplicating a standard stream (0. stdin, 1. stdout, 2. stderr), bộ mô tả tệp mới là

không phải WASI

Changed in version 3. 4. The new file descriptor is now non-inheritable.

os. dup2(fd , fd2, inheritable=True)

Sao chép bộ mô tả tệp fd thành fd2, đóng cái sau trước nếu cần. Trả lại fd2. Bộ mô tả tệp mới theo mặc định hoặc không thể kế thừa nếu có thể kế thừa là

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
92

không phải WASI

Đã thay đổi trong phiên bản 3. 4. Thêm tham số kế thừa tùy chọn.

Đã thay đổi trong phiên bản 3. 7. Trả lại fd2 khi thành công. Trước đây,

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
35 luôn được trả về.

os. fchmod(fd , mode)

Thay đổi chế độ của tệp do fd cung cấp thành chế độ số. Xem tài liệu để biết các giá trị có thể có của chế độ. Kể từ Python 3. 3, điều này tương đương với

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
35

Đưa ra một

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
36 với các đối số
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
38,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
39

Unix

Chức năng này bị giới hạn trên Emscripten và WASI, xem để biết thêm thông tin

os. fchown(fd , uid, gid)

Thay đổi chủ sở hữu và id nhóm của tệp do fd cung cấp thành uid và gid dạng số. Để giữ nguyên một trong các id, hãy đặt nó thành -1. Nhìn thấy. Kể từ Python 3. 3, điều này tương đương với

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
41

Nâng cao một

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
42 với các đối số
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
44,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
45,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
39

Unix

Chức năng này bị giới hạn trên Emscripten và WASI, xem để biết thêm thông tin

os. fdatasync(fd)

Buộc ghi tệp với filedescriptor fd vào đĩa. Không buộc cập nhật siêu dữ liệu

Unix

Ghi chú

Chức năng này không có trên MacOS

os. fpathconf(fd , name , /)

Return system configuration information relevant to an open file. name specifies the configuration value to retrieve; it may be a string which is the name of a defined system value; these names are specified in a number of standards (POSIX. 1, Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given in the

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
47 dictionary. For configuration variables not included in that mapping, passing an integer for name is also accepted

If name is a string and is not known, is raised. If a specific value for name is not supported by the host system, even if it is included in

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
47, an is raised with for the error number

As of Python 3. 3, this is equivalent to

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
52

Unix

os. fstat(fd)

Get the status of the file descriptor fd. Return a object

As of Python 3. 3, this is equivalent to

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
54

See also

The function

os. fstatvfs(fd , /)

Return information about the filesystem containing the file associated with file descriptor fd, like . Kể từ Python 3. 3, this is equivalent to

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
57

Unix

os. fsync(fd)

Force write of file with filedescriptor fd to disk. On Unix, this calls the native

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
58 function; on Windows, the MS
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
59 function

If you’re starting with a buffered Python f, first do

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
60, and then do
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
61, to ensure that all internal buffers associated with f are written to disk

Unix, Windows

os. ftruncate(fd , length , /)

Truncate the file corresponding to file descriptor fd, so that it is at most length bytes in size. As of Python 3. 3, this is equivalent to

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
62

Raises an

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
63 with arguments
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
64,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
65

Unix, Windows

Changed in version 3. 5. Added support for Windows

os. get_blocking(fd , /)

Get the blocking mode of the file descriptor.

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
92 if the flag is set,
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04 if the flag is cleared

See also and

Unix

Chức năng này bị giới hạn trên Emscripten và WASI, xem để biết thêm thông tin

New in version 3. 5

os. isatty(fd , /)

Return

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04 if the file descriptor fd is open and connected to a tty(-like) device, else
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
92

os. lockf(fd , cmd , len , /)

Apply, test or remove a POSIX lock on an open file descriptor. fd is an open file descriptor. cmd specifies the command to use - one of , , or . len specifies the section of the file to lock

Raises an

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
77 with arguments
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
64,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
79,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
80

Unix

New in version 3. 3

os. F_LOCKos. F_TLOCKos. F_ULOCKos. F_TEST

Flags that specify what action will take

Unix

New in version 3. 3

os. login_tty(fd , /)

Prepare the tty of which fd is a file descriptor for a new login session. Make the calling process a session leader; make the tty the controlling tty, the stdin, the stdout, and the stderr of the calling process; close fd

Unix, not Emscripten, not WASI

New in version 3. 11

os. lseek(fd , pos , how , /)

Set the current position of file descriptor fd to position pos, modified by how. or

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
83 to set the position relative to the beginning of the file; or
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
85 to set it relative to the current position; or
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
87 to set it relative to the end of the file. Return the new cursor position in bytes, starting from the beginning

os. SEEK_SETos. SEEK_CURos. SEEK_END

Parameters to the function. Giá trị của chúng lần lượt là 0, 1 và 2

New in version 3. 3. Một số hệ điều hành có thể hỗ trợ các giá trị bổ sung, như

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
89 hoặc
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
90.

os. open(path , flags , mode=0o777 , * , dir_fd=None)

Open the file path and set various flags according to flags and possibly its mode according to mode. When computing mode, the current umask value is first masked out. Return the file descriptor for the newly opened file. The new file descriptor is

For a description of the flag and mode values, see the C run-time documentation; flag constants (like and ) are defined in the module. In particular, on Windows adding is needed to open files in binary mode

This function can support with the dir_fd parameter

Raises an

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
95 with arguments
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
38,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
98

Changed in version 3. 4. The new file descriptor is now non-inheritable.

Ghi chú

This function is intended for low-level I/O. For normal usage, use the built-in function , which returns a with

with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)
00 and
with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)
01 methods (and many more). To wrap a file descriptor in a file object, use

New in version 3. 3. The dir_fd argument.

Changed in version 3. 5. If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising an exception (see PEP 475 for the rationale).

Changed in version 3. 6. Accepts a .

The following constants are options for the flags parameter to the function. They can be combined using the bitwise OR operator

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
4. Some of them are not available on all platforms. For descriptions of their availability and use, consult the open(2) manual page on Unix or the MSDN on Windows

os. O_RDONLYos. O_WRONLYos. O_RDWRos. O_APPENDos. O_CREATos. O_EXCLos. O_TRUNC

The above constants are available on Unix and Windows

os. O_DSYNCos. O_RSYNCos. O_SYNCos. O_NDELAYos. O_NONBLOCKos. O_NOCTTYos. O_CLOEXEC

The above constants are only available on Unix

Changed in version 3. 3. Add constant.

os. O_BINARYos. O_NOINHERITos. O_SHORT_LIVEDos. O_TEMPORARYos. O_RANDOMos. O_SEQUENTIALos. O_TEXT

The above constants are only available on Windows

os. O_EVTONLYos. O_FSYNCos. O_SYMLINKos. O_NOFOLLOW_ANY

The above constants are only available on macOS

Changed in version 3. 10. Add , , and constants.

os. O_ASYNCos. O_DIRECTos. O_DIRECTORYos. O_NOFOLLOWos. O_NOATIMEos. O_PATHos. O_TMPFILEos. O_SHLOCKos. O_EXLOCK

The above constants are extensions and not present if they are not defined by the C library

Changed in version 3. 4. Add on systems that support it. Add , only available on Linux Kernel 3. 11 or newer.

os. openpty()

Open a new pseudo-terminal pair. Return a pair of file descriptors

with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)
13 for the pty and the tty, respectively. The new file descriptors are . For a (slightly) more portable approach, use the module

Unix, not Emscripten, not WASI

Changed in version 3. 4. The new file descriptors are now non-inheritable.

os. pipe()

Create a pipe. Return a pair of file descriptors

with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)
15 usable for reading and writing, respectively. The new file descriptor is

Unix, Windows

Changed in version 3. 4. The new file descriptors are now non-inheritable.

os. pipe2(flags , /)

Create a pipe with flags set atomically. flags can be constructed by ORing together one or more of these values. , . Return a pair of file descriptors

with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)
15 usable for reading and writing, respectively

Unix, not Emscripten, not WASI

New in version 3. 3

os. posix_fallocate(fd , offset , len , /)

Ensures that enough disk space is allocated for the file specified by fd starting from offset and continuing for len bytes

Unix, not Emscripten

New in version 3. 3

os. posix_fadvise(fd , offset , len , advice , /)

Announces an intention to access data in a specific pattern thus allowing the kernel to make optimizations. The advice applies to the region of the file specified by fd starting at offset and continuing for len bytes. lời khuyên là một trong , , , , hoặc

Unix

New in version 3. 3

os. POSIX_FADV_NORMALos. POSIX_FADV_SEQUENTIALos. POSIX_FADV_RANDOMos. POSIX_FADV_NOREUSEos. POSIX_FADV_WILLNEEDos. POSIX_FADV_KHÔNG CẦN

Các cờ có thể được sử dụng trong lời khuyên chỉ định mẫu truy cập có khả năng được sử dụng

Unix

New in version 3. 3

os. trải rộng(fd , n, offset, /)

Đọc tối đa n byte từ bộ mô tả tệp fd tại vị trí bù trừ, giữ nguyên độ lệch tệp

Trả về một chuỗi byte chứa các byte đã đọc. Nếu đã đến cuối tệp được tham chiếu bởi fd, một đối tượng byte trống sẽ được trả về

Unix

New in version 3. 3

os. preadv(fd , bộ đệm, offset, flags=0, /)

Đọc từ bộ mô tả tệp fd ở vị trí bù vào bộ đệm có thể thay đổi, giữ nguyên phần bù tệp. Truyền dữ liệu vào từng bộ đệm cho đến khi đầy và sau đó chuyển sang bộ đệm tiếp theo trong chuỗi để giữ phần dữ liệu còn lại

Đối số cờ chứa OR theo bit bằng 0 hoặc nhiều cờ sau

Trả về tổng số byte thực sự đọc có thể nhỏ hơn tổng dung lượng của tất cả các đối tượng

Hệ điều hành có thể đặt giới hạn (giá trị

with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)
29) về số lượng bộ đệm có thể được sử dụng

Combine the functionality of and

Linux >= 2. 6. 30, FreeBSD >= 6. 0, OpenBSD >= 2. 7, AIX >= 7. 1

Using flags requires Linux >= 4. 6

New in version 3. 7

os. RWF_NOWAIT

Do not wait for data which is not immediately available. If this flag is specified, the system call will return instantly if it would have to read data from the backing storage or wait for a lock

If some data was successfully read, it will return the number of bytes read. If no bytes were read, it will return

with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)
32 and set errno to

Linux >= 4. 14

New in version 3. 7

os. RWF_HIPRI

High priority read/write. Allows block-based filesystems to use polling of the device, which provides lower latency, but may use additional resources

Currently, on Linux, this feature is usable only on a file descriptor opened using the flag

Linux >= 4. 6

New in version 3. 7

os. pwrite(fd , str , offset , /)

Write the bytestring in str to file descriptor fd at position of offset, leaving the file offset unchanged

Return the number of bytes actually written

Unix

New in version 3. 3

os. pwritev(fd , buffers , offset , flags=0 , /)

Write the buffers contents to file descriptor fd at a offset offset, leaving the file offset unchanged. buffers must be a sequence of . Buffers are processed in array order. Entire contents of the first buffer is written before proceeding to the second, and so on

Đối số cờ chứa OR theo bit bằng 0 hoặc nhiều cờ sau

Return the total number of bytes actually written

Hệ điều hành có thể đặt giới hạn (giá trị

with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)
29) về số lượng bộ đệm có thể được sử dụng

Combine the functionality of and

Linux >= 2. 6. 30, FreeBSD >= 6. 0, OpenBSD >= 2. 7, AIX >= 7. 1

Using flags requires Linux >= 4. 6

New in version 3. 7

os. RWF_DSYNC

Provide a per-write equivalent of the flag. This flag effect applies only to the data range written by the system call

Linux >= 4. 7

New in version 3. 7

os. RWF_SYNC

Provide a per-write equivalent of the flag. This flag effect applies only to the data range written by the system call

Linux >= 4. 7

New in version 3. 7

os. RWF_APPEND

Provide a per-write equivalent of the flag. This flag is meaningful only for , and its effect applies only to the data range written by the system call. The offset argument does not affect the write operation; the data is always appended to the end of the file. However, if the offset argument is

with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)
32, the current file offset is updated

Linux >= 4. 16

New in version 3. 10

os. read(fd , n , /)

Read at most n bytes from file descriptor fd

Trả về một chuỗi byte chứa các byte đã đọc. Nếu đã đến cuối tệp được tham chiếu bởi fd, một đối tượng byte trống sẽ được trả về

Ghi chú

This function is intended for low-level I/O and must be applied to a file descriptor as returned by or . To read a “file object” returned by the built-in function or by or , or , use its

with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)
00 or
with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)
57 methods

Changed in version 3. 5. If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising an exception (see PEP 475 for the rationale).

os. sendfile(out_fd , in_fd , offset , count)os. sendfile(out_fd , in_fd , offset , count , headers=() , trailers=() , flags=0)

Copy count bytes from file descriptor in_fd to file descriptor out_fd starting at offset. Return the number of bytes sent. When EOF is reached return

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
83

The first function notation is supported by all platforms that define

On Linux, if offset is given as

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
35, the bytes are read from the current position of in_fd and the position of in_fd is updated

The second case may be used on macOS and FreeBSD where headers and trailers are arbitrary sequences of buffers that are written before and after the data from in_fd is written. It returns the same as the first case

On macOS and FreeBSD, a value of

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
83 for count specifies to send until the end of in_fd is reached

All platforms support sockets as out_fd file descriptor, and some platforms allow other types (e. g. regular file, pipe) as well

Cross-platform applications should not use headers, trailers and flags arguments

Unix, not Emscripten, not WASI

Ghi chú

For a higher-level wrapper of , see

New in version 3. 3

Changed in version 3. 9. Parameters out and in was renamed to out_fd and in_fd.

os. set_blocking(fd , blocking , /)

Set the blocking mode of the specified file descriptor. Set the flag if blocking is

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
92, clear the flag otherwise

See also and

Unix

Chức năng này bị giới hạn trên Emscripten và WASI, xem để biết thêm thông tin

New in version 3. 5

os. SF_NODISKIOos. SF_MNOWAITos. SF_SYNC

Parameters to the function, if the implementation supports them

Unix, not Emscripten, not WASI

New in version 3. 3

os. SF_NOCACHE

Parameter to the function, if the implementation supports it. The data won’t be cached in the virtual memory and will be freed afterwards

Unix, not Emscripten, not WASI

New in version 3. 11

os. splice(src , dst , count , offset_src=None , offset_dst=None)

Transfer count bytes from file descriptor src, starting from offset offset_src, to file descriptor dst, starting from offset offset_dst. At least one of the file descriptors must refer to a pipe. If offset_src is None, then src is read from the current position; respectively for offset_dst. The offset associated to the file descriptor that refers to a pipe must be

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
35. Các tệp được trỏ bởi src và dst phải nằm trong cùng một hệ thống tệp, nếu không, một tệp được đặt thành

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. The copy is done as if both files are opened as binary

Upon successful completion, returns the number of bytes spliced to or from the pipe. A return value of 0 means end of input. If src refers to a pipe, then this means that there was no data to transfer, and it would not make sense to block because there are no writers connected to the write end of the pipe

Linux >= 2. 6. 17 with glibc >= 2. 5

New in version 3. 10

os. SPLICE_F_MOVEos. SPLICE_F_NONBLOCKos. SPLICE_F_MORE

New in version 3. 10

os. readv(fd , buffers , /)

Read from a file descriptor fd into a number of mutable buffers. Transfer data into each buffer until it is full and then move on to the next buffer in the sequence to hold the rest of the data

Trả về tổng số byte thực sự đọc có thể nhỏ hơn tổng dung lượng của tất cả các đối tượng

Hệ điều hành có thể đặt giới hạn (giá trị

with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)
29) về số lượng bộ đệm có thể được sử dụng

Unix

New in version 3. 3

os. tcgetpgrp(fd , /)

Return the process group associated with the terminal given by fd (an open file descriptor as returned by )

Unix, not WASI

os. tcsetpgrp(fd , pg , /)

Set the process group associated with the terminal given by fd (an open file descriptor as returned by ) to pg

Unix, not WASI

os. ttyname(fd , /)

Return a string which specifies the terminal device associated with file descriptor fd. If fd is not associated with a terminal device, an exception is raised

Unix

os. write(fd , str , /)

Write the bytestring in str to file descriptor fd

Return the number of bytes actually written

Ghi chú

This function is intended for low-level I/O and must be applied to a file descriptor as returned by or . To write a “file object” returned by the built-in function or by or , or or , use its

with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)
01 method

Changed in version 3. 5. If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising an exception (see PEP 475 for the rationale).

os. writev(fd , buffers , /)

Write the contents of buffers to file descriptor fd. buffers must be a sequence of . Buffers are processed in array order. Entire contents of the first buffer is written before proceeding to the second, and so on

Returns the total number of bytes actually written

Hệ điều hành có thể đặt giới hạn (giá trị

with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)
29) về số lượng bộ đệm có thể được sử dụng

Unix

New in version 3. 3

Querying the size of a terminal

New in version 3. 3

os. get_terminal_size(fd=STDOUT_FILENO , /)

Return the size of the terminal window as

with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)
90, tuple of type

The optional argument

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
64 (default
with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)
93, or standard output) specifies which file descriptor should be queried

If the file descriptor is not connected to a terminal, an is raised

is the high-level function which should normally be used,

with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)
96 is the low-level implementation

Unix, Windows

class os. terminal_size

A subclass of tuple, holding

with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)
90 of the terminal window size

columns

Width of the terminal window in characters

dòng

Height of the terminal window in characters

Inheritance of File Descriptors

New in version 3. 4

A file descriptor has an “inheritable” flag which indicates if the file descriptor can be inherited by child processes. Since Python 3. 4, file descriptors created by Python are non-inheritable by default

On UNIX, non-inheritable file descriptors are closed in child processes at the execution of a new program, other file descriptors are inherited

On Windows, non-inheritable handles and file descriptors are closed in child processes, except for standard streams (file descriptors 0, 1 and 2. stdin, stdout and stderr), which are always inherited. Using functions, all inheritable handles and all inheritable file descriptors are inherited. Using the module, all file descriptors except standard streams are closed, and inheritable handles are only inherited if the close_fds parameter is

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
92

On WebAssembly platforms

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
3 and
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
4, the file descriptor cannot be modified

os. get_inheritable(fd , /)

Get the “inheritable” flag of the specified file descriptor (a boolean)

os. set_inheritable(fd , inheritable , /)

Set the “inheritable” flag of the specified file descriptor

os. get_handle_inheritable(handle , /)

Get the “inheritable” flag of the specified handle (a boolean)

Windows

os. set_handle_inheritable(handle , inheritable , /)

Set the “inheritable” flag of the specified handle

Windows

Files and Directories

On some Unix platforms, many of these functions support one or more of these features

  • specifying a file descriptor. Normally the path argument provided to functions in the module must be a string specifying a file path. However, some functions now alternatively accept an open file descriptor for their path argument. The function will then operate on the file referred to by the descriptor. (For POSIX systems, Python will call the variant of the function prefixed with

    >>> import os
    >>> statinfo = os.stat('somefile.txt')
    >>> statinfo
    os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
    st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
    st_mtime=1297230027, st_ctime=1297230027)
    >>> statinfo.st_size
    264
    
    04 (e. g. call
    >>> import os
    >>> statinfo = os.stat('somefile.txt')
    >>> statinfo
    os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
    st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
    st_mtime=1297230027, st_ctime=1297230027)
    >>> statinfo.st_size
    264
    
    05 instead of
    >>> import os
    >>> statinfo = os.stat('somefile.txt')
    >>> statinfo
    os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
    st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
    st_mtime=1297230027, st_ctime=1297230027)
    >>> statinfo.st_size
    264
    
    06). )

    You can check whether or not path can be specified as a file descriptor for a particular function on your platform using . If this functionality is unavailable, using it will raise a

    If the function also supports dir_fd or follow_symlinks arguments, it’s an error to specify one of those when supplying path as a file descriptor

  • paths relative to directory descriptors. If dir_fd is not

    if os.access("myfile", os.R_OK):
        with open("myfile") as fp:
            return fp.read()
    return "some default data"
    
    35, it should be a file descriptor referring to a directory, and the path to operate on should be relative; path will then be relative to that directory. If the path is absolute, dir_fd is ignored. (For POSIX systems, Python will call the variant of the function with an
    >>> import os
    >>> statinfo = os.stat('somefile.txt')
    >>> statinfo
    os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
    st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
    st_mtime=1297230027, st_ctime=1297230027)
    >>> statinfo.st_size
    264
    
    10 suffix and possibly prefixed with
    >>> import os
    >>> statinfo = os.stat('somefile.txt')
    >>> statinfo
    os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
    st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
    st_mtime=1297230027, st_ctime=1297230027)
    >>> statinfo.st_size
    264
    
    04 (e. g. call
    >>> import os
    >>> statinfo = os.stat('somefile.txt')
    >>> statinfo
    os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
    st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
    st_mtime=1297230027, st_ctime=1297230027)
    >>> statinfo.st_size
    264
    
    12 instead of
    >>> import os
    >>> statinfo = os.stat('somefile.txt')
    >>> statinfo
    os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
    st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
    st_mtime=1297230027, st_ctime=1297230027)
    >>> statinfo.st_size
    264
    
    13)

    You can check whether or not dir_fd is supported for a particular function on your platform using . If it’s unavailable, using it will raise a

  • not following symlinks. If follow_symlinks is

    if os.access("myfile", os.R_OK):
        with open("myfile") as fp:
            return fp.read()
    return "some default data"
    
    92, and the last element of the path to operate on is a symbolic link, the function will operate on the symbolic link itself rather than the file pointed to by the link. (For POSIX systems, Python will call the
    >>> import os
    >>> statinfo = os.stat('somefile.txt')
    >>> statinfo
    os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
    st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
    st_mtime=1297230027, st_ctime=1297230027)
    >>> statinfo.st_size
    264
    
    17 variant of the function. )

    You can check whether or not follow_symlinks is supported for a particular function on your platform using . If it’s unavailable, using it will raise a

os. access(path , mode , * , dir_fd=None , effective_ids=False , follow_symlinks=True)

Use the real uid/gid to test for access to path. Note that most operations will use the effective uid/gid, therefore this routine can be used in a suid/sgid environment to test if the invoking user has the specified access to path. mode should be to test the existence of path, or it can be the inclusive OR of one or more of , , and to test permissions. Return if access is allowed, if not. See the Unix man page access(2) for more information

Chức năng này có thể hỗ trợ xác định và

If effective_ids is

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04, will perform its access checks using the effective uid/gid instead of the real uid/gid. effective_ids may not be supported on your platform; you can check whether or not it is available using . If it is unavailable, using it will raise a

Ghi chú

Sử dụng để kiểm tra xem người dùng có được phép sử dụng e. g. mở một tệp trước khi thực sự làm như vậy bằng cách sử dụng sẽ tạo ra một lỗ hổng bảo mật, bởi vì người dùng có thể lợi dụng khoảng thời gian ngắn giữa việc kiểm tra và mở tệp để thao tác với nó. Tốt hơn là sử dụng các kỹ thuật. Ví dụ

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"

được viết tốt hơn như

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()

Ghi chú

Các hoạt động I/O có thể không thành công ngay cả khi được chỉ ra rằng chúng sẽ thành công, đặc biệt đối với các hoạt động trên hệ thống tệp mạng có thể có ngữ nghĩa quyền vượt ra ngoài mô hình bit quyền POSIX thông thường

Đã thay đổi trong phiên bản 3. 3. Đã thêm các tham số dir_fd, effect_ids và follow_symlinks.

Changed in version 3. 6. Accepts a .

os. F_OKos. R_OKos. W_OKos. X_OK

Values to pass as the mode parameter of to test the existence, readability, writability and executability of path, respectively

os. chdir(path)

Change the current working directory to path

This function can support . The descriptor must refer to an opened directory, not an open file

This function can raise and subclasses such as , , and

Raises an

>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
st_mtime=1297230027, st_ctime=1297230027)
>>> statinfo.st_size
264
38 with argument
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37

New in version 3. 3. Added support for specifying path as a file descriptor on some platforms.

Changed in version 3. 6. Accepts a .

os. chflags(path , flags , * , follow_symlinks=True)

Set the flags of path to the numeric flags. flags may take a combination (bitwise OR) of the following values (as defined in the module)

This function can support

Raises an

>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
st_mtime=1297230027, st_ctime=1297230027)
>>> statinfo.st_size
264
53 with arguments
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
98

Unix, not Emscripten, not WASI

New in version 3. 3. The follow_symlinks argument.

Changed in version 3. 6. Accepts a .

os. chmod(path , mode , * , dir_fd=None , follow_symlinks=True)

Change the mode of path to the numeric mode. mode may take one of the following values (as defined in the module) or bitwise ORed combinations of them

This function can support , and

Ghi chú

Although Windows supports , you can only set the file’s read-only flag with it (via the

>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
st_mtime=1297230027, st_ctime=1297230027)
>>> statinfo.st_size
264
62 and
>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
st_mtime=1297230027, st_ctime=1297230027)
>>> statinfo.st_size
264
61 constants or a corresponding integer value). All other bits are ignored

Chức năng này bị giới hạn trên Emscripten và WASI, xem để biết thêm thông tin

Đưa ra một

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
36 với các đối số
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
38,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
39

New in version 3. 3. Added support for specifying path as an open file descriptor, and the dir_fd and follow_symlinks arguments.

Changed in version 3. 6. Accepts a .

os. chown(path , uid , gid , * , dir_fd=None , follow_symlinks=True)

Change the owner and group id of path to the numeric uid and gid. To leave one of the ids unchanged, set it to -1

This function can support , and

Xem chức năng cấp cao hơn chấp nhận tên ngoài id số

Nâng cao một

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
42 với các đối số
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
44,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
45,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
39

Unix

Chức năng này bị giới hạn trên Emscripten và WASI, xem để biết thêm thông tin

New in version 3. 3. Added support for specifying path as an open file descriptor, and the dir_fd and follow_symlinks arguments.

Changed in version 3. 6. Supports a .

os. chroot(path)

Change the root directory of the current process to path

Unix, not Emscripten, not WASI

Changed in version 3. 6. Accepts a .

os. fchdir(fd)

Change the current working directory to the directory represented by the file descriptor fd. The descriptor must refer to an opened directory, not an open file. As of Python 3. 3, this is equivalent to

>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
st_mtime=1297230027, st_ctime=1297230027)
>>> statinfo.st_size
264
89

Raises an

>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
st_mtime=1297230027, st_ctime=1297230027)
>>> statinfo.st_size
264
38 with argument
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37

Unix

os. getcwd()

Return a string representing the current working directory

os. getcwdb()

Return a bytestring representing the current working directory

Changed in version 3. 8. The function now uses the UTF-8 encoding on Windows, rather than the ANSI code page. see PEP 529 for the rationale. The function is no longer deprecated on Windows.

os. lchflags(path , flags)

Set the flags of path to the numeric flags, like , but do not follow symbolic links. As of Python 3. 3, this is equivalent to

>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
st_mtime=1297230027, st_ctime=1297230027)
>>> statinfo.st_size
264
93

Raises an

>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
st_mtime=1297230027, st_ctime=1297230027)
>>> statinfo.st_size
264
53 with arguments
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
98

Unix, not Emscripten, not WASI

Changed in version 3. 6. Accepts a .

os. lchmod(path , mode)

Change the mode of path to the numeric mode. If path is a symlink, this affects the symlink rather than the target. See the docs for for possible values of mode. As of Python 3. 3, this is equivalent to

>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
st_mtime=1297230027, st_ctime=1297230027)
>>> statinfo.st_size
264
98

Đưa ra một

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
36 với các đối số
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
38,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
39

Unix

Changed in version 3. 6. Accepts a .

os. lchown(path , uid , gid)

Change the owner and group id of path to the numeric uid and gid. This function will not follow symbolic links. As of Python 3. 3, this is equivalent to

os.stat in os.supports_dir_fd
03

Nâng cao một

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
42 với các đối số
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
44,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
45,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
39

Unix

Changed in version 3. 6. Accepts a .

os. link(src , dst , * , src_dir_fd=None , dst_dir_fd=None , follow_symlinks=True)

Create a hard link pointing to src named dst

This function can support specifying src_dir_fd and/or dst_dir_fd to supply , and

Raises an

os.stat in os.supports_dir_fd
09 with arguments
os.stat in os.supports_dir_fd
10,
os.stat in os.supports_dir_fd
11,
os.stat in os.supports_dir_fd
12,
os.stat in os.supports_dir_fd
13

Unix, Windows

Changed in version 3. 2. Added Windows support.

New in version 3. 3. Added the src_dir_fd, dst_dir_fd, and follow_symlinks arguments.

Changed in version 3. 6. Accepts a for src and dst.

os. listdir(path='. ')

Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order, and does not include the special entries

os.stat in os.supports_dir_fd
14 and
os.stat in os.supports_dir_fd
15 even if they are present in the directory. If a file is removed from or added to the directory during the call of this function, whether a name for that file be included is unspecified

path may be a . If path is of type

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
7 (directly or indirectly through the interface), the filenames returned will also be of type
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
7; in all other circumstances, they will be of type
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
10

This function can also support ; the file descriptor must refer to a directory

Raises an

os.stat in os.supports_dir_fd
20 with argument
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37

Ghi chú

To encode

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
10 filenames to
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
7, use

See also

The function returns directory entries along with file attribute information, giving better performance for many common use cases

Changed in version 3. 2. The path parameter became optional.

New in version 3. 3. Added support for specifying path as an open file descriptor.

Changed in version 3. 6. Accepts a .

os. lstat(đường dẫn , *, dir_fd=None)

Thực hiện tương đương với một cuộc gọi hệ thống

os.stat in os.supports_dir_fd
26 trên đường dẫn đã cho. Tương tự như , nhưng không theo các liên kết tượng trưng. Return a object

On platforms that do not support symbolic links, this is an alias for

As of Python 3. 3, this is equivalent to

os.stat in os.supports_dir_fd
30

This function can also support

See also

The function

Changed in version 3. 2. Added support for Windows 6. 0 (Vista) symbolic links.

Changed in version 3. 3. Added the dir_fd parameter.

Changed in version 3. 6. Accepts a .

Changed in version 3. 8. On Windows, now opens reparse points that represent another path (name surrogates), including symbolic links and directory junctions. Other kinds of reparse points are resolved by the operating system as for .

os. mkdir(path , mode=0o777 , * , dir_fd=None)

Create a directory named path with numeric mode mode

If the directory already exists, is raised. If a parent directory in the path does not exist, is raised

On some systems, mode is ignored. Where it is used, the current umask value is first masked out. If bits other than the last 9 (i. e. the last 3 digits of the octal representation of the mode) are set, their meaning is platform-dependent. On some platforms, they are ignored and you should call explicitly to set them

This function can also support

It is also possible to create temporary directories; see the module’s function

Raises an

os.stat in os.supports_dir_fd
38 with arguments
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
38,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
39

New in version 3. 3. The dir_fd argument.

Changed in version 3. 6. Accepts a .

os. makedirs(name , mode=0o777 , exist_ok=False)

Recursive directory creation function. Like , but makes all intermediate-level directories needed to contain the leaf directory

The mode parameter is passed to for creating the leaf directory; see for how it is interpreted. Để đặt các bit cho phép tệp của bất kỳ thư mục mẹ nào mới được tạo, bạn có thể đặt ô trước khi gọi. The file permission bits of existing parent directories are not changed

If exist_ok is

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
92 (the default), a is raised if the target directory already exists

Ghi chú

will become confused if the path elements to create include (eg. “. ” on UNIX systems)

This function handles UNC paths correctly

Raises an

os.stat in os.supports_dir_fd
38 with arguments
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
38,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
39

New in version 3. 2. The exist_ok parameter.

Changed in version 3. 4. 1. Before Python 3. 4. 1, if exist_ok was

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04 and the directory existed, would still raise an error if mode did not match the mode of the existing directory. Since this behavior was impossible to implement safely, it was removed in Python 3. 4. 1. See bpo-21082.

Changed in version 3. 6. Accepts a .

Changed in version 3. 7. The mode argument no longer affects the file permission bits of newly created intermediate-level directories.

os. mkfifo(path , mode=0o666 , * , dir_fd=None)

Create a FIFO (a named pipe) named path with numeric mode mode. The current umask value is first masked out from the mode

This function can also support

FIFOs are pipes that can be accessed like regular files. FIFOs exist until they are deleted (for example with ). Generally, FIFOs are used as rendezvous between “client” and “server” type processes. the server opens the FIFO for reading, and the client opens it for writing. Note that doesn’t open the FIFO — it just creates the rendezvous point

Unix, not Emscripten, not WASI

New in version 3. 3. The dir_fd argument.

Changed in version 3. 6. Accepts a .

os. mknod(path , mode=0o600 , device=0 , * , dir_fd=None)

Create a filesystem node (file, device special file or named pipe) named path. mode specifies both the permissions to use and the type of node to be created, being combined (bitwise OR) with one of

os.stat in os.supports_dir_fd
57,
os.stat in os.supports_dir_fd
58,
os.stat in os.supports_dir_fd
59, and
os.stat in os.supports_dir_fd
60 (those constants are available in ). For
os.stat in os.supports_dir_fd
58 and
os.stat in os.supports_dir_fd
59, device defines the newly created device special file (probably using ), otherwise it is ignored

This function can also support

Unix, not Emscripten, not WASI

New in version 3. 3. The dir_fd argument.

Changed in version 3. 6. Accepts a .

os. major(device , /)

Extract the device major number from a raw device number (usually the

os.stat in os.supports_dir_fd
65 or
os.stat in os.supports_dir_fd
66 field from
>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
st_mtime=1297230027, st_ctime=1297230027)
>>> statinfo.st_size
264
40)

os. minor(device , /)

Extract the device minor number from a raw device number (usually the

os.stat in os.supports_dir_fd
65 or
os.stat in os.supports_dir_fd
66 field from
>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
st_mtime=1297230027, st_ctime=1297230027)
>>> statinfo.st_size
264
40)

os. makedev(major , minor , /)

Compose a raw device number from the major and minor device numbers

os. pathconf(path , name)

Return system configuration information relevant to a named file. name specifies the configuration value to retrieve; it may be a string which is the name of a defined system value; these names are specified in a number of standards (POSIX. 1, Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given in the

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
47 dictionary. For configuration variables not included in that mapping, passing an integer for name is also accepted

If name is a string and is not known, is raised. If a specific value for name is not supported by the host system, even if it is included in

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
47, an is raised with for the error number

This function can support

Unix

Changed in version 3. 6. Accepts a .

os. pathconf_names

Dictionary mapping names accepted by and to the integer values defined for those names by the host operating system. This can be used to determine the set of names known to the system

Unix

os. readlink(path , * , dir_fd=None)

Return a string representing the path to which the symbolic link points. The result may be either an absolute or relative pathname; if it is relative, it may be converted to an absolute pathname using

os.stat in os.supports_dir_fd
78

Nếu đường dẫn là một đối tượng chuỗi (trực tiếp hoặc gián tiếp thông qua giao diện), kết quả cũng sẽ là một đối tượng chuỗi và lệnh gọi có thể gây ra lỗi UnicodeDecodeError. Nếu đường dẫn là đối tượng byte (trực tiếp hoặc gián tiếp), kết quả sẽ là đối tượng byte

This function can also support

Khi cố gắng giải quyết một đường dẫn có thể chứa liên kết, hãy sử dụng để xử lý chính xác sự khác biệt về nền tảng và đệ quy

Unix, Windows

Changed in version 3. 2. Added support for Windows 6. 0 (Vista) symbolic links.

New in version 3. 3. The dir_fd argument.

Đã thay đổi trong phiên bản 3. 6. Accepts a on Unix.

Changed in version 3. 8. Accepts a and a bytes object on Windows.

Changed in version 3. 8. Added support for directory junctions, and changed to return the substitution path (which typically includes

os.stat in os.supports_dir_fd
81 prefix) rather than the optional “print name” field that was previously returned.

os. remove(path , * , dir_fd=None)

Remove (delete) the file path. If path is a directory, an is raised. Sử dụng để loại bỏ các thư mục. If the file does not exist, a is raised

This function can support

On Windows, attempting to remove a file that is in use causes an exception to be raised; on Unix, the directory entry is removed but the storage allocated to the file is not made available until the original file is no longer in use

This function is semantically identical to

Raises an

os.stat in os.supports_dir_fd
86 with arguments
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
39

New in version 3. 3. The dir_fd argument.

Changed in version 3. 6. Accepts a .

os. removedirs(name)

Remove directories recursively. Works like except that, if the leaf directory is successfully removed, tries to successively remove every parent directory mentioned in path until an error is raised (which is ignored, because it generally means that a parent directory is not empty). For example,

os.stat in os.supports_dir_fd
91 will first remove the directory
os.stat in os.supports_dir_fd
92, and then remove
os.stat in os.supports_dir_fd
93 and
os.stat in os.supports_dir_fd
94 if they are empty. Raises if the leaf directory could not be successfully removed

Raises an

os.stat in os.supports_dir_fd
86 with arguments
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
39

Changed in version 3. 6. Accepts a .

os. rename(src , dst , * , src_dir_fd=None , dst_dir_fd=None)

Rename the file or directory src to dst. If dst exists, the operation will fail with an subclass in a number of cases

On Windows, if dst exists a is always raised. The operation may fail if src and dst are on different filesystems. Use to support moves to a different filesystem

On Unix, if src is a file and dst is a directory or vice-versa, an or a will be raised respectively. If both are directories and dst is empty, dst will be silently replaced. If dst is a non-empty directory, an is raised. If both are files, dst will be replaced silently if the user has permission. The operation may fail on some Unix flavors if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement)

This function can support specifying src_dir_fd and/or dst_dir_fd to supply

If you want cross-platform overwriting of the destination, use

Raises an

os.access in os.supports_effective_ids
06 with arguments
os.stat in os.supports_dir_fd
10,
os.stat in os.supports_dir_fd
11,
os.stat in os.supports_dir_fd
12,
os.stat in os.supports_dir_fd
13

New in version 3. 3. The src_dir_fd and dst_dir_fd arguments.

Changed in version 3. 6. Accepts a for src and dst.

os. renames(old , new)

Recursive directory or file renaming function. Works like , 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 away using

Ghi chú

This function can fail with the new directory structure made if you lack permissions needed to remove the leaf directory or file

Raises an

os.access in os.supports_effective_ids
06 with arguments
os.stat in os.supports_dir_fd
10,
os.stat in os.supports_dir_fd
11,
os.stat in os.supports_dir_fd
12,
os.stat in os.supports_dir_fd
13

Changed in version 3. 6. Accepts a for old and new.

os. replace(src , dst , * , src_dir_fd=None , dst_dir_fd=None)

Rename the file or directory src to dst. If dst is a non-empty directory, will be raised. If dst exists and is a file, it will be replaced silently if the user has permission. The operation may fail if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement)

This function can support specifying src_dir_fd and/or dst_dir_fd to supply

Raises an

os.access in os.supports_effective_ids
06 with arguments
os.stat in os.supports_dir_fd
10,
os.stat in os.supports_dir_fd
11,
os.stat in os.supports_dir_fd
12,
os.stat in os.supports_dir_fd
13

New in version 3. 3

Changed in version 3. 6. Accepts a for src and dst.

os. rmdir(path , * , dir_fd=None)

Remove (delete) the directory path. If the directory does not exist or is not empty, a or an is raised respectively. In order to remove whole directory trees, can be used

This function can support

Raises an

os.access in os.supports_effective_ids
27 with arguments
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
39

New in version 3. 3. The dir_fd parameter.

Changed in version 3. 6. Accepts a .

os. scandir(đường dẫn='. ')

Return an iterator of objects corresponding to the entries in the directory given by path. The entries are yielded in arbitrary order, and the special entries

os.stat in os.supports_dir_fd
14 and
os.stat in os.supports_dir_fd
15 are not included. If a file is removed from or added to the directory after creating the iterator, whether an entry for that file be included is unspecified

Using instead of can significantly increase the performance of code that also needs file type or file attribute information, because objects expose this information if the operating system provides it when scanning a directory. All methods may perform a system call, but and usually only require a system call for symbolic links; always requires a system call on Unix but only requires one for symbolic links on Windows

path may be a . If path is of type

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
7 (directly or indirectly through the interface), the type of the and attributes of each will be
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
7; in all other circumstances, they will be of type
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
10

This function can also support ; the file descriptor must refer to a directory

Raises an

os.access in os.supports_effective_ids
47 with argument
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37

The iterator supports the protocol and has the following method

scandir. close()

Close the iterator and free acquired resources

This is called automatically when the iterator is exhausted or garbage collected, or when an error happens during iterating. However it is advisable to call it explicitly or use the statement

New in version 3. 6

The following example shows a simple use of to display all the files (excluding directories) in the given path that don’t start with

os.stat in os.supports_dir_fd
14. The
os.access in os.supports_effective_ids
53 call will generally not make an additional system call

with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)

Ghi chú

On Unix-based systems, uses the system’s opendir() and readdir() functions. On Windows, it uses the Win32 FindFirstFileW and FindNextFileW functions

New in version 3. 5

New in version 3. 6. Added support for the protocol and the method. If a iterator is neither exhausted nor explicitly closed a will be emitted in its destructor.

The function accepts a

Changed in version 3. 7. Added support for on Unix.

class os. DirEntry

Object yielded by to expose the file path and other file attributes of a directory entry

will provide as much of this information as possible without making additional system calls. When a

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
55 or
os.stat in os.supports_dir_fd
26 system call is made, the
os.access in os.supports_effective_ids
30 object will cache the result

os.access in os.supports_effective_ids
30 phiên bản không nhằm mục đích lưu trữ trong cấu trúc dữ liệu tồn tại lâu dài;

Because the

os.access in os.supports_effective_ids
30 methods can make operating system calls, they may also raise . If you need very fine-grained control over errors, you can catch when calling one of the
os.access in os.supports_effective_ids
30 methods and handle as appropriate

To be directly usable as a ,

os.access in os.supports_effective_ids
30 implements the interface

Attributes and methods on a

os.access in os.supports_effective_ids
30 instance are as follows

name

The entry’s base filename, relative to the path argument

The attribute will be

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
7 if the path argument is of type
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
7 and
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
10 otherwise. Use to decode byte filenames

con đường

The entry’s full path name. equivalent to

os.access in os.supports_effective_ids
80 where scandir_path is the path argument. Đường dẫn chỉ tuyệt đối nếu đối số đường dẫn là tuyệt đối. If the path argument was a , the attribute is the same as the attribute

The attribute will be

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
7 if the path argument is of type
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
7 and
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
10 otherwise. Use to decode byte filenames

inode()

Return the inode number of the entry

The result is cached on the

os.access in os.supports_effective_ids
30 object. Use
os.access in os.supports_effective_ids
93 to fetch up-to-date information

On the first, uncached call, a system call is required on Windows but not on Unix

is_dir(* , follow_symlinks=True)

Return

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04 if this entry is a directory or a symbolic link pointing to a directory; return
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
92 if the entry is or points to any other kind of file, or if it doesn’t exist anymore

If follow_symlinks is

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
92, return
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04 only if this entry is a directory (without following symlinks); return
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
92 if the entry is any other kind of file or if it doesn’t exist anymore

The result is cached on the

os.access in os.supports_effective_ids
30 object, with a separate cache for follow_symlinks
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04 and
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
92. Call along with to fetch up-to-date information

Trong cuộc gọi đầu tiên, không được lưu vào bộ đệm, hầu hết các trường hợp không yêu cầu cuộc gọi hệ thống. Specifically, for non-symlinks, neither Windows or Unix require a system call, except on certain Unix file systems, such as network file systems, that return

os.chdir in os.supports_fd
04. If the entry is a symlink, a system call will be required to follow the symlink unless follow_symlinks is
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
92

This method can raise , such as , but is caught and not raised

is_file(* , follow_symlinks=True)

Return

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04 if this entry is a file or a symbolic link pointing to a file; return
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
92 if the entry is or points to a directory or other non-file entry, or if it doesn’t exist anymore

If follow_symlinks is

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
92, return
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04 only if this entry is a file (without following symlinks); return
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
92 if the entry is a directory or other non-file entry, or if it doesn’t exist anymore

The result is cached on the

os.access in os.supports_effective_ids
30 object. Caching, system calls made, and exceptions raised are as per

is_symlink()

Return

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04 if this entry is a symbolic link (even if broken); return
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
92 if the entry points to a directory or any kind of file, or if it doesn’t exist anymore

The result is cached on the

os.access in os.supports_effective_ids
30 object. Call to fetch up-to-date information

On the first, uncached call, no system call is required in most cases. Specifically, neither Windows or Unix require a system call, except on certain Unix file systems, such as network file systems, that return

os.chdir in os.supports_fd
04

This method can raise , such as , but is caught and not raised

stat(* , follow_symlinks=True)

Return a object for this entry. This method follows symbolic links by default; to stat a symbolic link add the

os.chdir in os.supports_fd
25 argument

On Unix, this method always requires a system call. On Windows, it only requires a system call if follow_symlinks is

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04 and the entry is a reparse point (for example, a symbolic link or directory junction)

On Windows, the

os.chdir in os.supports_fd
27,
os.stat in os.supports_dir_fd
65 and
os.chdir in os.supports_fd
29 attributes of the are always set to zero. Call to get these attributes

The result is cached on the

os.access in os.supports_effective_ids
30 object, with a separate cache for follow_symlinks
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04 and
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
92. Call to fetch up-to-date information

Note that there is a nice correspondence between several attributes and methods of

os.access in os.supports_effective_ids
30 and of . In particular, the
os.access in os.supports_effective_ids
42 attribute has the same meaning, as do the
os.access in os.supports_effective_ids
37,
os.access in os.supports_effective_ids
38,
os.chdir in os.supports_fd
41 and
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
55 methods

New in version 3. 5

Changed in version 3. 6. Added support for the interface. Added support for paths on Windows.

os. stat(path , * , dir_fd=None , follow_symlinks=True)

Get the status of a file or a file descriptor. Perform the equivalent of a

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
55 system call on the given path. path may be specified as either a string or bytes – directly or indirectly through the interface – or as an open file descriptor. Return a object

This function normally follows symlinks; to stat a symlink add the argument

os.chdir in os.supports_fd
25, or use

This function can support and

On Windows, passing

os.chdir in os.supports_fd
25 will disable following all name-surrogate reparse points, which includes symlinks and directory junctions. Other types of reparse points that do not resemble links or that the operating system is unable to follow will be opened directly. When following a chain of multiple links, this may result in the original link being returned instead of the non-link that prevented full traversal. To obtain stat results for the final path in this case, use the function to resolve the path name as far as possible and call on the result. This does not apply to dangling symlinks or junction points, which will raise the usual exceptions

Example

>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
st_mtime=1297230027, st_ctime=1297230027)
>>> statinfo.st_size
264

See also

and functions

New in version 3. 3. Added the dir_fd and follow_symlinks arguments, specifying a file descriptor instead of a path.

Changed in version 3. 6. Accepts a .

Changed in version 3. 8. On Windows, all reparse points that can be resolved by the operating system are now followed, and passing

os.chdir in os.supports_fd
25 disables following all name surrogate reparse points. If the operating system reaches a reparse point that it is not able to follow, stat now returns the information for the original path as if
os.chdir in os.supports_fd
25 had been specified instead of raising an error.

class os. stat_result

Object whose attributes correspond roughly to the members of the

>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
st_mtime=1297230027, st_ctime=1297230027)
>>> statinfo.st_size
264
40 structure. Nó được sử dụng cho kết quả của , và

Attributes

st_mode

File mode. file type and file mode bits (permissions)

st_ino

Platform dependent, but if non-zero, uniquely identifies the file for a given value of

os.stat in os.supports_dir_fd
65. Typically

  • the inode number on Unix,

  • the file index on Windows

st_dev

Identifier of the device on which this file resides

st_nlink

Number of hard links

st_uid

User identifier of the file owner

st_gid

Group identifier of the file owner

st_size

Size of the file in bytes, if it is a regular file or a symbolic link. The size of a symbolic link is the length of the pathname it contains, without a terminating null byte

Timestamps

st_atime

Time of most recent access expressed in seconds

st_mtime

Time of most recent content modification expressed in seconds

st_ctime

Platform dependent

  • the time of most recent metadata change on Unix,

  • the time of creation on Windows, expressed in seconds

st_atime_ns

Time of most recent access expressed in nanoseconds as an integer

st_mtime_ns

Time of most recent content modification expressed in nanoseconds as an integer

st_ctime_ns

Platform dependent

  • the time of most recent metadata change on Unix,

  • the time of creation on Windows, expressed in nanoseconds as an integer

Ghi chú

The exact meaning and resolution of the , , and attributes depend on the operating system and the file system. For example, on Windows systems using the FAT or FAT32 file systems, has 2-second resolution, and has only 1-day resolution. See your operating system documentation for details

Similarly, although , , and are always expressed in nanoseconds, many systems do not provide nanosecond precision. Trên các hệ thống cung cấp độ chính xác nano giây, đối tượng dấu phẩy động được sử dụng để lưu trữ , và không thể lưu giữ tất cả đối tượng đó và do đó sẽ hơi không chính xác. If you need the exact timestamps you should always use , , and

On some Unix systems (such as Linux), the following attributes may also be available

st_blocks

Number of 512-byte blocks allocated for file. This may be smaller than /512 when the file has holes

st_blksize

“Preferred” blocksize for efficient file system I/O. Ghi vào một tệp trong các phần nhỏ hơn có thể gây ra đọc-sửa-viết lại không hiệu quả

st_rdev

Type of device if an inode device

st_flags

User defined flags for file

On other Unix systems (such as FreeBSD), the following attributes may be available (but may be only filled out if root tries to use them)

st_gen

số thế hệ tập tin

st_birthtime

Thời gian tạo tập tin

Trên Solaris và các công cụ phái sinh, các thuộc tính sau cũng có thể khả dụng

st_fstype

Chuỗi xác định duy nhất loại hệ thống tệp chứa tệp

Trên các hệ thống macOS, các thuộc tính sau cũng có thể khả dụng

st_rsize

Kích thước thật của tập tin

st_creator

Người tạo tập tin

st_type

Loại tệp

Trên các hệ thống Windows, các thuộc tính sau cũng có sẵn

st_file_attributes

Thuộc tính tệp Windows.

os.chdir in os.supports_fd
77 member of the
os.chdir in os.supports_fd
78 structure returned by
os.chdir in os.supports_fd
79. Xem hằng số
os.chdir in os.supports_fd
80 trong mô-đun

st_reparse_tag

Khi đã đặt

os.chdir in os.supports_fd
83, trường này chứa thẻ xác định loại điểm phân tích lại. Xem hằng số
os.chdir in os.supports_fd
84 trong mô-đun

Mô-đun tiêu chuẩn định nghĩa các hàm và hằng hữu ích để trích xuất thông tin từ cấu trúc

>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
st_mtime=1297230027, st_ctime=1297230027)
>>> statinfo.st_size
264
40. (Trên Windows, một số mục chứa đầy giá trị giả. )

Để tương thích ngược, một thể hiện cũng có thể truy cập dưới dạng một bộ gồm ít nhất 10 số nguyên cung cấp các phần tử quan trọng nhất (và di động) của cấu trúc

>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
st_mtime=1297230027, st_ctime=1297230027)
>>> statinfo.st_size
264
40, theo thứ tự , , , , , , , , ,. Nhiều mục khác có thể được thêm vào cuối bởi một số triển khai. Để tương thích với các phiên bản Python cũ hơn, việc truy cập dưới dạng bộ dữ liệu luôn trả về số nguyên

Mới trong phiên bản 3. 3. Đã thêm , và thành viên.

Mới trong phiên bản 3. 5. Đã thêm thành viên trên Windows.

Đã thay đổi trong phiên bản 3. 5. Windows hiện trả về chỉ mục tệp như khi khả dụng.

Mới trong phiên bản 3. 7. Đã thêm thành viên vào Solaris/công cụ phái sinh.

Mới trong phiên bản 3. 8. Đã thêm thành viên trên Windows.

Đã thay đổi trong phiên bản 3. 8. Trên Windows, thành viên hiện xác định các tệp đặc biệt là

os.stat in os.supports_follow_symlinks
09,
os.stat in os.supports_follow_symlinks
10 hoặc
os.stat in os.supports_follow_symlinks
11 khi thích hợp.

os. statvfs(đường dẫn)

Thực hiện cuộc gọi hệ thống

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
56 trên đường dẫn đã cho. Giá trị trả về là một đối tượng có các thuộc tính mô tả hệ thống tệp trên đường dẫn đã cho và tương ứng với các thành viên của cấu trúc
os.stat in os.supports_follow_symlinks
13, cụ thể là.
os.stat in os.supports_follow_symlinks
14,
os.stat in os.supports_follow_symlinks
15,
os.stat in os.supports_follow_symlinks
16,
os.stat in os.supports_follow_symlinks
17,
os.stat in os.supports_follow_symlinks
18,
os.stat in os.supports_follow_symlinks
19,
os.stat in os.supports_follow_symlinks
20,
os.stat in os.supports_follow_symlinks
21,
os.stat in os.supports_follow_symlinks
22,
os.stat in os.supports_follow_symlinks
23,
os.stat in os.supports_follow_symlinks
24

Hai hằng số cấp mô-đun được xác định cho các cờ bit của thuộc tính

os.stat in os.supports_follow_symlinks
22. nếu
os.stat in os.supports_follow_symlinks
26 được đặt, hệ thống tệp được gắn ở chế độ chỉ đọc và nếu
os.stat in os.supports_follow_symlinks
27 được đặt, ngữ nghĩa của các bit setuid/setgid bị vô hiệu hóa hoặc không được hỗ trợ

Các hằng số cấp mô-đun bổ sung được xác định cho các hệ thống dựa trên GNU/glibc. Đây là

os.stat in os.supports_follow_symlinks
28 (không cho phép truy cập vào các tệp đặc biệt của thiết bị),
os.stat in os.supports_follow_symlinks
29 (không cho phép thực thi chương trình),
os.stat in os.supports_follow_symlinks
30 (ghi được đồng bộ hóa cùng một lúc),
os.stat in os.supports_follow_symlinks
31 (cho phép khóa bắt buộc trên FS),
os.stat in os.supports_follow_symlinks
32 (ghi trên tệp/thư mục/liên kết tượng trưng),
os.stat in os.supports_follow_symlinks
33

This function can support

Unix

Đã thay đổi trong phiên bản 3. 2. Các hằng số

os.stat in os.supports_follow_symlinks
26 và
os.stat in os.supports_follow_symlinks
27 đã được thêm vào.

New in version 3. 3. Added support for specifying path as an open file descriptor.

Đã thay đổi trong phiên bản 3. 4. Các hằng số

os.stat in os.supports_follow_symlinks
28,
os.stat in os.supports_follow_symlinks
29,
os.stat in os.supports_follow_symlinks
30,
os.stat in os.supports_follow_symlinks
31,
os.stat in os.supports_follow_symlinks
32,
os.stat in os.supports_follow_symlinks
33,
os.stat in os.supports_follow_symlinks
34,
os.stat in os.supports_follow_symlinks
35,
os.stat in os.supports_follow_symlinks
36 và
os.stat in os.supports_follow_symlinks
37.

Changed in version 3. 6. Accepts a .

Mới trong phiên bản 3. 7. Đã thêm

os.stat in os.supports_follow_symlinks
24.

os. supports_dir_fd

Một đối tượng cho biết chức năng nào trong mô-đun chấp nhận bộ mô tả tệp mở cho tham số dir_fd của chúng. Các nền tảng khác nhau cung cấp các tính năng khác nhau và chức năng cơ bản mà Python sử dụng để triển khai tham số dir_fd không khả dụng trên tất cả các nền tảng mà Python hỗ trợ. Để đảm bảo tính nhất quán, các hàm có thể hỗ trợ dir_fd luôn cho phép chỉ định tham số, nhưng sẽ đưa ra một ngoại lệ nếu chức năng được sử dụng khi nó không khả dụng cục bộ. (Specifying

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
35 for dir_fd is always supported on all platforms. )

Để kiểm tra xem một chức năng cụ thể có chấp nhận một bộ mô tả tệp đang mở cho tham số dir_fd của nó hay không, hãy sử dụng toán tử

os.stat in os.supports_follow_symlinks
54 trên
os.stat in os.supports_follow_symlinks
55. Ví dụ: biểu thức này ước tính thành
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04 nếu chấp nhận bộ mô tả tệp mở cho dir_fd trên nền tảng cục bộ

os.stat in os.supports_dir_fd

Hiện tại các tham số dir_fd chỉ hoạt động trên nền tảng Unix;

New in version 3. 3

os. supports_effect_ids

Một đối tượng cho biết liệu có cho phép chỉ định

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04 cho tham số effect_ids của nó trên nền tảng cục bộ hay không. (Chỉ định
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
92 cho hiệu quả_ids luôn được hỗ trợ trên tất cả các nền tảng. ) Nếu nền tảng cục bộ hỗ trợ nó, bộ sưu tập sẽ chứa ;

Biểu thức này đánh giá là

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04 nếu hỗ trợ
os.stat in os.supports_follow_symlinks
65 trên nền tảng địa phương

os.access in os.supports_effective_ids

Hiện tại effect_ids chỉ được hỗ trợ trên nền tảng Unix;

New in version 3. 3

os. supports_fd

Một đối tượng cho biết chức năng nào trong mô-đun cho phép chỉ định tham số đường dẫn của chúng dưới dạng bộ mô tả tệp mở trên nền tảng cục bộ. Các nền tảng khác nhau cung cấp các tính năng khác nhau và chức năng cơ bản mà Python sử dụng để chấp nhận các bộ mô tả tệp mở vì các đối số đường dẫn không khả dụng trên tất cả các nền tảng mà Python hỗ trợ

Để xác định xem một chức năng cụ thể có cho phép chỉ định một bộ mô tả tệp mở cho tham số đường dẫn của nó hay không, hãy sử dụng toán tử

os.stat in os.supports_follow_symlinks
54 trên
os.stat in os.supports_follow_symlinks
69. Ví dụ: biểu thức này ước tính thành
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04 nếu chấp nhận bộ mô tả tệp mở cho đường dẫn trên nền tảng cục bộ của bạn

os.chdir in os.supports_fd

New in version 3. 3

os. supports_follow_symlinks

Một đối tượng cho biết chức năng nào trong mô-đun chấp nhận

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
92 cho tham số follow_symlinks của chúng trên nền tảng cục bộ. Các nền tảng khác nhau cung cấp các tính năng khác nhau và chức năng cơ bản mà Python sử dụng để triển khai follow_symlinks không khả dụng trên tất cả các nền tảng mà Python hỗ trợ. Để đảm bảo tính nhất quán, các hàm có thể hỗ trợ follow_symlinks luôn cho phép chỉ định tham số, nhưng sẽ đưa ra một ngoại lệ nếu chức năng được sử dụng khi nó không khả dụng cục bộ. (Chỉ định
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04 cho follow_symlinks luôn được hỗ trợ trên tất cả các nền tảng. )

Để kiểm tra xem một chức năng cụ thể có chấp nhận

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
92 cho tham số follow_symlinks của nó hay không, hãy sử dụng toán tử
os.stat in os.supports_follow_symlinks
54 trên
os.stat in os.supports_follow_symlinks
78. Ví dụ: biểu thức này ước tính thành
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04 nếu bạn có thể chỉ định
os.chdir in os.supports_fd
25 khi gọi trên nền tảng địa phương

os.stat in os.supports_follow_symlinks

New in version 3. 3

os. liên kết tượng trưng(src , dst, target_is_directory=False, *, dir_fd=None)

Tạo một liên kết tượng trưng trỏ đến src có tên là dst

Trên Windows, một liên kết tượng trưng đại diện cho một tệp hoặc một thư mục và không biến thành mục tiêu một cách linh hoạt. Nếu có mục tiêu, loại liên kết tượng trưng sẽ được tạo để khớp. Mặt khác, liên kết tượng trưng sẽ được tạo dưới dạng thư mục nếu target_is_directory là

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04 hoặc liên kết tượng trưng tệp (mặc định) nếu ngược lại. Trên các nền tảng không phải Windows, target_is_directory bị bỏ qua

This function can support

Ghi chú

Trên các phiên bản Windows 10 mới hơn, các tài khoản không có đặc quyền có thể tạo liên kết tượng trưng nếu Chế độ nhà phát triển được bật. Khi Chế độ nhà phát triển không khả dụng/được bật, thì cần phải có đặc quyền SeCreateSymbolicLinkPrivilege hoặc quy trình phải được chạy với tư cách quản trị viên

được nâng lên khi chức năng được gọi bởi người dùng không có đặc quyền

Đưa ra một

os.stat in os.supports_follow_symlinks
84 với các đối số
os.stat in os.supports_dir_fd
10,
os.stat in os.supports_dir_fd
11,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
39

Unix, Windows

Chức năng này bị giới hạn trên Emscripten và WASI, xem để biết thêm thông tin

Changed in version 3. 2. Added support for Windows 6. 0 (Vista) symbolic links.

Mới trong phiên bản 3. 3. Added the dir_fd argument, and now allow target_is_directory on non-Windows platforms.

Changed in version 3. 6. Accepts a for src and dst.

Đã thay đổi trong phiên bản 3. 8. Đã thêm hỗ trợ cho các liên kết tượng trưng không được nâng cao trên Windows với Chế độ nhà phát triển.

os. đồng bộ hóa()

Buộc ghi mọi thứ vào đĩa

Unix

New in version 3. 3

os. cắt ngắn(đường dẫn , độ dài)

Cắt bớt tệp tương ứng với đường dẫn, sao cho nó có kích thước tối đa là byte

This function can support

Tăng một

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
63 với các đối số
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
65

Unix, Windows

New in version 3. 3

Changed in version 3. 5. Added support for Windows

Changed in version 3. 6. Accepts a .

os. hủy liên kết(đường dẫn , *, dir_fd=None)

Xóa (xóa) đường dẫn tệp. Chức năng này giống hệt về mặt ngữ nghĩa với ; . Vui lòng xem tài liệu để biết thêm thông tin

Raises an

os.stat in os.supports_dir_fd
86 with arguments
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
39

New in version 3. 3. The dir_fd parameter.

Changed in version 3. 6. Accepts a .

os. utime(đường dẫn , lần, *, [ns, ]dir_fd=None, follow_symlinks=True)

Đặt thời gian truy cập và sửa đổi của tệp được chỉ định bởi đường dẫn

có hai tham số tùy chọn, thời gian và ns. These specify the times set on path and are used as follows

  • Nếu ns được chỉ định, nó phải là 2 bộ có dạng _______18_______98 trong đó mỗi phần tử là một int biểu thị nano giây

  • Nếu thời gian không phải là _______25_______35, thì nó phải là 2 bộ có dạng _______21_______00 trong đó mỗi phần tử là một int hoặc float thể hiện giây

  • Nếu thời gian là

    if os.access("myfile", os.R_OK):
        with open("myfile") as fp:
            return fp.read()
    return "some default data"
    
    35 và ns không được chỉ định, điều này tương đương với việc chỉ định
    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
    
    02 trong đó cả hai thời gian đều là thời gian hiện tại

Có lỗi khi chỉ định bộ dữ liệu cho cả thời gian và ns

Lưu ý rằng thời gian chính xác mà bạn đặt ở đây có thể không được trả lại bằng lệnh gọi tiếp theo, tùy thuộc vào độ phân giải mà hệ điều hành của bạn ghi lại thời gian truy cập và sửa đổi; . Cách tốt nhất để duy trì thời gian chính xác là sử dụng các trường st_atime_ns và st_mtime_ns từ đối tượng kết quả với tham số ns để

This function can support , and

Đưa ra một

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
07 với các đối số
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37,
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
09,
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
10,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
39

Mới trong phiên bản 3. 3. Đã thêm hỗ trợ để chỉ định đường dẫn dưới dạng bộ mô tả tệp đang mở và các tham số dir_fd, follow_symlinks và ns.

Changed in version 3. 6. Accepts a .

os. đi bộ(top , topdown=True, onerror=None, followlinks=False)

Tạo tên tệp trong cây thư mục bằng cách di chuyển cây từ trên xuống hoặc từ dưới lên. Đối với mỗi thư mục trong cây bắt nguồn từ đầu thư mục (bao gồm cả đầu), nó tạo ra 3-tuple

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
12

dirpath là một chuỗi, đường dẫn đến thư mục. dirnames là danh sách tên của các thư mục con trong dirpath (bao gồm các liên kết tượng trưng đến các thư mục và không bao gồm

os.stat in os.supports_dir_fd
14 và
os.stat in os.supports_dir_fd
15). tên tệp là danh sách tên của các tệp không phải thư mục trong dirpath. Lưu ý rằng tên trong danh sách không chứa thành phần đường dẫn. Để có đường dẫn đầy đủ (bắt đầu bằng top) tới một tệp hoặc thư mục trong dirpath, hãy thực hiện _
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
15. Danh sách có được sắp xếp hay không tùy thuộc vào hệ thống tệp. If a file is removed from or added to the dirpath directory during generating the lists, whether a name for that file be included is unspecified

Nếu topdown đối số tùy chọn là

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04 hoặc không được chỉ định, bộ ba cho một thư mục được tạo trước bộ ba cho bất kỳ thư mục con nào của nó (các thư mục được tạo từ trên xuống). Nếu từ trên xuống là
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
92, bộ ba cho một thư mục được tạo sau bộ ba cho tất cả các thư mục con của nó (các thư mục được tạo từ dưới lên). Bất kể giá trị của topdown là gì, danh sách các thư mục con được truy xuất trước khi các bộ dữ liệu cho thư mục và các thư mục con của nó được tạo

Khi topdown là

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04, người gọi có thể sửa đổi danh sách dirnames tại chỗ (có thể sử dụng hoặc gán lát cắt) và sẽ chỉ chuyển tiếp vào các thư mục con có tên vẫn còn trong dirnames; . Sửa đổi dirnames khi topdown là
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
92 không ảnh hưởng đến hoạt động của walk, bởi vì ở chế độ từ dưới lên, các thư mục trong dirnames được tạo trước khi chính dirpath được tạo

Theo mặc định, các lỗi từ cuộc gọi sẽ bị bỏ qua. Nếu onerror đối số tùy chọn được chỉ định, nó phải là một hàm; . Nó có thể báo lỗi để tiếp tục đi bộ hoặc đưa ra ngoại lệ để hủy bỏ đi bộ. Lưu ý rằng tên tệp có sẵn dưới dạng thuộc tính

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
26 của đối tượng ngoại lệ

Theo mặc định, sẽ không đi xuống các liên kết tượng trưng giải quyết các thư mục. Đặt các liên kết theo dõi thành

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04 để truy cập các thư mục được trỏ tới bởi các liên kết tượng trưng, ​​trên các hệ thống hỗ trợ chúng

Ghi chú

Xin lưu ý rằng việc đặt các liên kết theo dõi thành

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04 có thể dẫn đến đệ quy vô hạn nếu một liên kết trỏ đến thư mục mẹ của chính nó. không theo dõi các thư mục mà nó đã truy cập

Ghi chú

Nếu bạn chuyển một tên đường dẫn tương đối, đừng thay đổi thư mục làm việc hiện tại giữa các lần nối lại. không bao giờ thay đổi thư mục hiện tại và giả định rằng người gọi nó cũng không

Ví dụ này hiển thị số byte được lấy bởi các tệp không phải thư mục trong mỗi thư mục bên dưới thư mục bắt đầu, ngoại trừ việc nó không tìm trong bất kỳ thư mục con CVS nào

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

Trong ví dụ tiếp theo (triển khai đơn giản của ), đi bộ từ dưới lên trên cây là cần thiết, không cho phép xóa thư mục trước khi thư mục trống

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
0

Đưa ra một

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
35 với các đối số
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
36,
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
37,
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
38,
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
39

Changed in version 3. 5. Hàm này hiện gọi thay vì , làm cho hàm nhanh hơn bằng cách giảm số lần gọi thành.

Changed in version 3. 6. Accepts a .

os. đi bộ(top='. ' , topdown=True, onerror=None, *, follow_symlinks=False, dir_fd=None)

Điều này hoạt động chính xác như , ngoại trừ việc nó tạo ra 4-tuple

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
44 và nó hỗ trợ
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
39

dirpath, dirnames và tên tệp giống hệt với đầu ra và dirfd là một bộ mô tả tệp đề cập đến thư mục dirpath

Chức năng này luôn hỗ trợ và. Tuy nhiên, xin lưu ý rằng, không giống như các chức năng khác, giá trị mặc định cho follow_symlinks là

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
92

Ghi chú

Vì mang lại các bộ mô tả tệp, chúng chỉ hợp lệ cho đến bước lặp tiếp theo, vì vậy bạn nên sao chép chúng (e. g. with ) nếu bạn muốn giữ chúng lâu hơn

Ví dụ này hiển thị số byte được lấy bởi các tệp không phải thư mục trong mỗi thư mục bên dưới thư mục bắt đầu, ngoại trừ việc nó không tìm trong bất kỳ thư mục con CVS nào

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
1

Trong ví dụ tiếp theo, đi bộ từ dưới lên trên cây là điều cần thiết. không cho phép xóa thư mục trước khi thư mục trống

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
2

Đưa ra một

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
52 với các đối số
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
36,
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
37,
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
38,
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
56,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
39

Unix

New in version 3. 3

Changed in version 3. 6. Accepts a .

Đã thay đổi trong phiên bản 3. 7. Đã thêm hỗ trợ cho đường dẫn.

os. memfd_create(tên[ , . MFD_CLOEXEC flags=os.MFD_CLOEXEC])

Create an anonymous file and return a file descriptor that refers to it. các cờ phải là một trong các hằng số

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
59 có sẵn trên hệ thống (hoặc kết hợp ORed theo bit của chúng). Theo mặc định, bộ mô tả tệp mới là

Tên được cung cấp trong tên được sử dụng làm tên tệp và sẽ được hiển thị dưới dạng đích của liên kết tượng trưng tương ứng trong thư mục

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
60. Tên được hiển thị luôn có tiền tố là
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
61 và chỉ phục vụ cho mục đích gỡ lỗi. Tên không ảnh hưởng đến hành vi của bộ mô tả tệp và do đó, nhiều tệp có thể có cùng tên mà không có bất kỳ tác dụng phụ nào

Linux >= 3. 17 với glibc >= 2. 27

New in version 3. 8

os. MFD_CLOEXECos. MFD_ALLOW_SEALINGos. MFD_HUGETLBos. MFD_HUGE_SHIFTos. MFD_HUGE_MASKos. MFD_HUGE_64KBos. MFD_HUGE_512KBos. MFD_HUGE_1 MBos. MFD_HUGE_2MBos. MFD_HUGE_8MBos. MFD_HUGE_16MBos. MFD_HUGE_32MBos. MFD_HUGE_256MBos. MFD_HUGE_512MBos. MFD_HUGE_1GBos. MFD_HUGE_2GBos. MFD_HUGE_16GB

Những cờ này có thể được chuyển đến

Linux >= 3. 17 with glibc >= 2. 27

Các cờ

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
63 chỉ khả dụng kể từ Linux 4. 14

New in version 3. 8

os. eventfd(initval[ , . EFD_CLOEXEC flags=os.EFD_CLOEXEC])

Tạo và trả về một bộ mô tả tệp sự kiện. Các bộ mô tả tệp hỗ trợ thô và có kích thước bộ đệm là 8, , và tương tự. Xem trang man eventfd(2) để biết thêm thông tin. Theo mặc định, bộ mô tả tệp mới là

initval là giá trị ban đầu của bộ đếm sự kiện. Giá trị ban đầu phải là số nguyên không dấu 32 bit. Xin lưu ý rằng giá trị ban đầu được giới hạn ở một int không dấu 32 bit mặc dù bộ đếm sự kiện là một số nguyên 64 bit không dấu với giá trị tối đa là 264-2

cờ có thể được xây dựng từ , , và

Nếu được chỉ định và bộ đếm sự kiện khác không, trả về 1 và giảm bộ đếm đi một

Nếu không được chỉ định và bộ đếm sự kiện khác không, trả về giá trị bộ đếm sự kiện hiện tại và đặt lại bộ đếm về 0

Nếu bộ đếm sự kiện bằng 0 và không được chỉ định, hãy chặn

tăng bộ đếm sự kiện. Ghi khối nếu thao tác ghi sẽ tăng bộ đếm lên giá trị lớn hơn 264-2

Example

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
3

Linux >= 2. 6. 27 với glibc >= 2. 8

New in version 3. 10

os. eventfd_read(fd)

Đọc giá trị từ bộ mô tả tệp và trả về int không dấu 64 bit. Chức năng không xác minh rằng fd là một

Linux >= 2. 6. 27

New in version 3. 10

os. eventfd_write(fd , giá trị)

Thêm giá trị vào một bộ mô tả tập tin. giá trị phải là một int không dấu 64 bit. Chức năng không xác minh rằng fd là một

Linux >= 2. 6. 27

New in version 3. 10

os. EFD_CLOEXEC

Đặt cờ close-on-exec cho bộ mô tả tệp mới

Linux >= 2. 6. 27

New in version 3. 10

os. EFD_NONBLOCK

Đặt cờ trạng thái cho bộ mô tả tệp mới

Linux >= 2. 6. 27

New in version 3. 10

os. EFD_SEMAPHORE

Cung cấp ngữ nghĩa giống như semaphore để đọc từ bộ mô tả tệp. Khi đọc bộ đếm bên trong được giảm đi một

Linux >= 2. 6. 30

New in version 3. 10

Thuộc tính mở rộng Linux

New in version 3. 3

Các chức năng này chỉ có sẵn trên Linux

os. getxattr(đường dẫn , thuộc tính, *, follow_symlinks=True)

Trả về giá trị của thuộc tính thuộc tính hệ thống tập tin mở rộng cho đường dẫn. attribute can be bytes or str (directly or indirectly through the interface). If it is str, it is encoded with the filesystem encoding

This function can support and

Đưa ra một

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
87 với các đối số
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37,
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
89

Đã thay đổi trong phiên bản 3. 6. Chấp nhận đường dẫn và thuộc tính for.

os. listxattr(đường dẫn=Không có, *, follow_symlinks=True)

Trả về danh sách các thuộc tính hệ thống tệp mở rộng trên đường dẫn. Các thuộc tính trong danh sách được biểu diễn dưới dạng các chuỗi được giải mã bằng mã hóa hệ thống tệp. Nếu đường dẫn là

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
35, sẽ kiểm tra thư mục hiện tại

This function can support and

Đưa ra một

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
92 với lập luận
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37

Changed in version 3. 6. Accepts a .

os. removexattr(đường dẫn , thuộc tính, *, follow_symlinks=True)

Xóa thuộc tính thuộc tính hệ thống tệp mở rộng khỏi đường dẫn. thuộc tính phải là byte hoặc str (trực tiếp hoặc gián tiếp thông qua giao diện). Nếu nó là một chuỗi, nó được mã hóa bằng

This function can support and

Tăng một

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
95 với các đối số
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37,
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
89

Đã thay đổi trong phiên bản 3. 6. Chấp nhận đường dẫn và thuộc tính for.

os. setxattr(đường dẫn , thuộc tính, value, flags=0, *, follow_symlinks=True)

Đặt thuộc tính thuộc tính hệ thống tệp mở rộng trên đường dẫn đến giá trị. thuộc tính phải là byte hoặc str không có NUL nhúng (trực tiếp hoặc gián tiếp thông qua giao diện). Nếu nó là một str, nó được mã hóa bằng. cờ có thể là hoặc. Nếu được đưa ra và thuộc tính không tồn tại,

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
002 sẽ được nâng lên. Nếu được cung cấp và thuộc tính đã tồn tại, thuộc tính sẽ không được tạo và
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
004 sẽ tăng

This function can support and

Ghi chú

Một lỗi trong các phiên bản nhân Linux nhỏ hơn 2. 6. 39 khiến đối số flags bị bỏ qua trên một số hệ thống tệp

Tăng một

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
005 với các đối số
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37,
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
89,
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
75,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
98

Đã thay đổi trong phiên bản 3. 6. Chấp nhận đường dẫn và thuộc tính for.

os. XATTR_SIZE_MAX

Kích thước tối đa giá trị của thuộc tính mở rộng có thể là. Hiện tại, đây là 64 KiB trên Linux

os. XATTR_CREATE

Đây là một giá trị có thể có cho đối số flags trong. Nó chỉ ra rằng hoạt động phải tạo ra một thuộc tính

os. XATTR_REPLACE

Đây là một giá trị có thể có cho đối số flags trong. Nó cho biết hoạt động phải thay thế một thuộc tính hiện có

Quản lý quy trình

Các chức năng này có thể được sử dụng để tạo và quản lý các quy trình

The various functions take a list of arguments for the new program loaded into the process. Trong mỗi trường hợp, đối số đầu tiên trong số này được chuyển đến chương trình mới dưới dạng tên riêng của nó chứ không phải là đối số mà người dùng có thể đã nhập vào một dòng lệnh. Đối với lập trình viên C, đây là ____25_______013 được chuyển đến ____25_______014 của chương trình. Ví dụ:

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
015 sẽ chỉ in
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
016 trên đầu ra tiêu chuẩn;

os. hủy bỏ()

Tạo tín hiệu

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
018 cho quy trình hiện tại. Trên Unix, hành vi mặc định là tạo ra một kết xuất lõi; . Xin lưu ý rằng việc gọi hàm này sẽ không gọi trình xử lý tín hiệu Python đã đăng ký cho
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
018 với

os. add_dll_directory(đường dẫn)

Thêm đường dẫn vào đường dẫn tìm kiếm DLL

Đường dẫn tìm kiếm này được sử dụng khi giải quyết các phụ thuộc cho các mô-đun mở rộng đã nhập (bản thân mô-đun được giải quyết thông qua ) và cũng bởi

Xóa thư mục bằng cách gọi close() trên đối tượng được trả về hoặc sử dụng nó trong một câu lệnh

Xem tài liệu của Microsoft để biết thêm thông tin về cách tải tệp DLL

Tăng một

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
025 với lập luận
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37

Windows

Mới trong phiên bản 3. 8. Các phiên bản trước của CPython sẽ giải quyết các tệp DLL bằng hành vi mặc định cho quy trình hiện tại. Điều này dẫn đến sự không nhất quán, chẳng hạn như đôi khi chỉ tìm kiếm

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
027 hoặc thư mục làm việc hiện tại và các chức năng của hệ điều hành như
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
028 không có tác dụng.

Trong 3. 8, the two primary ways DLLs are loaded now explicitly override the process-wide behavior to ensure consistency. Xem thông tin về cập nhật thư viện

os. execl(đường dẫn , arg0 . , arg1, ...)os. execle(đường dẫn , arg0 . , arg1, ... , env)os. execlp(tệp , arg0 . , arg1, ...)os. execlpe(tệp , arg0 . , arg1, ... , env)os. execv(đường dẫn , args . )os.execve(path , args . , env)os.execvp(file , args . )os.execvpe(tệp , args, env)

These functions all execute a new program, replacing the current process; they do not return. Trên Unix, tệp thực thi mới được tải vào quy trình hiện tại và sẽ có id quy trình giống như người gọi. Lỗi sẽ được báo cáo là ngoại lệ

Quy trình hiện tại được thay thế ngay lập tức. Các đối tượng và bộ mô tả tệp đang mở không được xóa, vì vậy nếu có thể có dữ liệu được lưu vào bộ đệm trên các tệp đang mở này, bạn nên xóa chúng bằng cách sử dụng

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
030 hoặc trước khi gọi một hàm

Các biến thể “l” và “v” của các hàm khác nhau về cách truyền đối số dòng lệnh. Các biến thể “l” có lẽ là dễ làm việc nhất nếu số lượng tham số được cố định khi viết mã; . Các biến thể của v v rất tốt khi số lượng tham số thay đổi, với các đối số được truyền trong một danh sách hoặc bộ dữ liệu dưới dạng tham số args. Trong cả hai trường hợp, các đối số của tiến trình con phải bắt đầu bằng tên của lệnh đang được chạy, nhưng điều này không được thực thi

Các biến thể bao gồm một chữ “p” ở gần cuối (, , và ) sẽ sử dụng biến môi trường

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
027 để định vị tệp chương trình. Khi môi trường đang được thay thế (sử dụng một trong các biến thể, được thảo luận trong đoạn tiếp theo), môi trường mới được sử dụng làm nguồn của biến
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
027. Các biến thể khác, , , và , sẽ không sử dụng biến
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
027 để định vị tệp thực thi;

Đối với , , và (lưu ý rằng tất cả các giá trị này đều kết thúc bằng “e”), tham số env phải là một ánh xạ được sử dụng để xác định các biến môi trường cho quy trình mới (các biến này được sử dụng thay cho môi trường của quy trình hiện tại);

Đối với một số nền tảng, đường dẫn cũng có thể được chỉ định làm bộ mô tả tệp mở. Chức năng này có thể không được hỗ trợ trên nền tảng của bạn; . Nếu nó không có sẵn, sử dụng nó sẽ tăng

Tăng một

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
058 với các đối số
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37,
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
060,
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
061

Unix, Windows, not Emscripten, not WASI

Mới trong phiên bản 3. 3. Đã thêm hỗ trợ để chỉ định đường dẫn làm bộ mô tả tệp mở cho.

Changed in version 3. 6. Accepts a .

os. _exit(n)

Thoát khỏi quy trình với trạng thái n, mà không gọi trình xử lý dọn dẹp, xóa bộ đệm stdio, v.v.

Ghi chú

Cách tiêu chuẩn để thoát là

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
063. thông thường chỉ nên được sử dụng trong tiến trình con sau một

Các mã thoát sau đây được xác định và có thể được sử dụng với , mặc dù chúng không bắt buộc. Chúng thường được sử dụng cho các chương trình hệ thống được viết bằng Python, chẳng hạn như chương trình gửi lệnh bên ngoài của máy chủ thư

Ghi chú

Một số trong số này có thể không khả dụng trên tất cả các nền tảng Unix, vì có một số biến thể. Các hằng số này được xác định ở nơi chúng được xác định bởi nền tảng cơ bản

os. EX_OK

Mã thoát có nghĩa là không có lỗi xảy ra. Có thể được lấy từ giá trị được xác định của

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
067 trên một số nền tảng. Nói chung có giá trị bằng không

Unix, Windows

os. EX_USAGE

Mã thoát có nghĩa là lệnh đã được sử dụng không chính xác, chẳng hạn như khi đưa ra số lượng đối số sai

Unix, not Emscripten, not WASI

os. EX_DATAERR

Mã thoát có nghĩa là dữ liệu đầu vào không chính xác

Unix, not Emscripten, not WASI

os. EX_NOINPUT

Mã thoát có nghĩa là tệp đầu vào không tồn tại hoặc không thể đọc được

Unix, not Emscripten, not WASI

os. EX_NOUSER

Mã thoát có nghĩa là người dùng được chỉ định không tồn tại

Unix, not Emscripten, not WASI

os. EX_NOHOST

Mã thoát có nghĩa là một máy chủ được chỉ định không tồn tại

Unix, not Emscripten, not WASI

os. EX_UNAVAILABLE

Mã thoát có nghĩa là dịch vụ được yêu cầu không khả dụng

Unix, not Emscripten, not WASI

os. EX_SOFTWARE

Mã thoát có nghĩa là đã phát hiện lỗi phần mềm nội bộ

Unix, not Emscripten, not WASI

os. EX_OSERR

Mã thoát có nghĩa là đã phát hiện thấy lỗi hệ điều hành, chẳng hạn như không thể rẽ nhánh hoặc tạo đường ống

Unix, not Emscripten, not WASI

os. EX_OSFILE

Mã thoát có nghĩa là một số tệp hệ thống không tồn tại, không thể mở được hoặc có một số loại lỗi khác

Unix, not Emscripten, not WASI

os. EX_CANTCREAT

Mã thoát có nghĩa là không thể tạo tệp đầu ra do người dùng chỉ định

Unix, not Emscripten, not WASI

os. EX_IOERR

Mã thoát có nghĩa là đã xảy ra lỗi khi thực hiện I/O trên một số tệp

Unix, not Emscripten, not WASI

os. EX_TEMPFAIL

Mã thoát có nghĩa là đã xảy ra lỗi tạm thời. Điều này cho biết điều gì đó có thể không thực sự là lỗi, chẳng hạn như kết nối mạng không thể thực hiện được trong một thao tác có thể thử lại

Unix, not Emscripten, not WASI

os. EX_PROTOCOL

Mã thoát có nghĩa là trao đổi giao thức là bất hợp pháp, không hợp lệ hoặc không hiểu

Unix, not Emscripten, not WASI

os. EX_NOPERM

Mã thoát có nghĩa là không có đủ quyền để thực hiện thao tác (nhưng không dành cho các sự cố hệ thống tệp)

Unix, not Emscripten, not WASI

os. EX_CONFIG

Exit code that means that some kind of configuration error occurred

Unix, not Emscripten, not WASI

os. EX_NOTFOUND

Mã thoát có nghĩa là "không tìm thấy mục nhập"

Unix, not Emscripten, not WASI

os. ngã ba()

Ngã ba một tiến trình con. Trả về

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
83 trong phần tử con và id tiến trình của phần tử con trong phần tử gốc. Nếu một lỗi xảy ra được nâng lên

Lưu ý rằng một số nền tảng bao gồm FreeBSD <= 6. 3 và Cygwin đã biết các sự cố khi sử dụng

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
6 từ một luồng

Tăng

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
071 mà không có đối số

Đã thay đổi trong phiên bản 3. 8. Việc gọi

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
6 trong một trình thông dịch phụ không còn được hỗ trợ nữa ( được nâng lên).

Cảnh báo

Xem các ứng dụng sử dụng mô-đun SSL với fork()

Unix, not Emscripten, not WASI

os. phân nhánh()

Chia nhánh một tiến trình con, sử dụng thiết bị đầu cuối giả mới làm thiết bị đầu cuối điều khiển của con. Trả về một cặp

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
075, trong đó pid là
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
83 ở phần tử con, id tiến trình của phần tử con mới ở phần gốc và fd là bộ mô tả tệp của phần cuối chính của thiết bị đầu cuối giả. Để có cách tiếp cận di động hơn, hãy sử dụng mô-đun. If an error occurs is raised

Tăng một

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
079 mà không có đối số

Đã thay đổi trong phiên bản 3. 8. Gọi

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
080 trong trình thông dịch phụ không còn được hỗ trợ nữa ( được nâng lên).

Unix, not Emscripten, not WASI

os. giết(pid , sig, /)

Gửi tín hiệu sig đến quá trình pid. Các hằng số cho các tín hiệu cụ thể có sẵn trên nền tảng máy chủ được xác định trong mô-đun

các cửa sổ. Các tín hiệu và là các tín hiệu đặc biệt chỉ có thể được gửi đến các tiến trình điều khiển có chung một cửa sổ điều khiển, e. g. , một số quy trình con. Bất kỳ giá trị nào khác cho sig sẽ khiến quy trình bị hủy vô điều kiện bởi API TerminateProcess và mã thoát sẽ được đặt thành sig. Phiên bản Windows của bổ sung xử lý quá trình bị giết

Xem thêm

Nâng cao một

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
087 với các đối số
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
088,
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
089

Unix, Windows, not Emscripten, not WASI

Mới trong phiên bản 3. 2. Hỗ trợ Windows.

os. killpg(pgid , sig , /)

Gửi sig tín hiệu đến pgid nhóm quy trình

Tăng một

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
090 với các đối số
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
091,
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
089

Unix, not Emscripten, not WASI

os. tốt(tăng , /)

Thêm phần gia tăng vào “sự tốt đẹp” của quy trình. Trả lại vẻ đẹp như mới

Unix, not Emscripten, not WASI

os. pidfd_open(pid , cờ=0)

Trả về một bộ mô tả tệp đề cập đến quá trình pid. Bộ mô tả này có thể được sử dụng để thực hiện quản lý quy trình mà không cần các cuộc đua và tín hiệu. Đối số flags được cung cấp cho các phần mở rộng trong tương lai;

Xem trang man pidfd_open(2) để biết thêm chi tiết

Linux >= 5. 3

Mới trong phiên bản 3. 9

os. khóa(op , /)

Khóa các đoạn chương trình vào bộ nhớ. Giá trị của op (được xác định trong

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
093) xác định phân đoạn nào bị khóa

Unix, not Emscripten, not WASI

os. popen(cmd , mode='r' , buffering=- 1)

Mở một đường ống đến hoặc từ lệnh cmd. Giá trị trả về là một đối tượng tệp mở được kết nối với đường ống, có thể được đọc hoặc ghi tùy thuộc vào chế độ là

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
094 (mặc định) hay
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
095. Đối số đệm có cùng ý nghĩa với đối số tương ứng với hàm tích hợp. Đối tượng tệp được trả về đọc hoặc ghi chuỗi văn bản thay vì byte

Phương thức

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
097 trả về nếu quy trình con đã thoát thành công hoặc mã trả về của quy trình con nếu có lỗi. Trên các hệ thống POSIX, nếu mã trả về là số dương, mã này biểu thị giá trị trả về của quy trình được dịch trái một byte. Nếu mã trả về là số âm, quá trình đã bị kết thúc bởi tín hiệu được cung cấp bởi giá trị phủ định của mã trả về. (Ví dụ: giá trị trả về có thể là
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
099 nếu quy trình con bị hủy. ) Trên các hệ thống Windows, giá trị trả về chứa mã trả về số nguyên đã ký từ tiến trình con

Trên Unix, có thể được sử dụng để chuyển đổi kết quả của phương thức

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
097 (trạng thái thoát) thành mã thoát nếu nó không phải là
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
35. Trên Windows, kết quả của phương pháp
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
097 trực tiếp là mã thoát (hoặc
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
35)

Điều này được thực hiện bằng cách sử dụng;

không phải Emscripten, không phải WASI

Ghi chú

Các mã hóa ảnh hưởng được sử dụng cho nội dung cmd và đường ống

là một trình bao bọc đơn giản xung quanh. Sử dụng hoặc để kiểm soát các tùy chọn như mã hóa

os. posix_spawn(đường dẫn , argv, env, *, file_actions=None, setpgroup=None, resetids=False, setsid=False, setsigmask=(), setsigdef=(), scheduler=None)

Kết thúc API thư viện

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
110 C để sử dụng từ Python

Hầu hết người dùng nên sử dụng thay vì

The positional-only arguments path, args, and env are similar to

Tham số đường dẫn là đường dẫn đến tệp thực thi. Đường dẫn phải chứa một thư mục. Sử dụng để truyền tệp thực thi mà không có thư mục

Đối số file_actions có thể là một chuỗi các bộ dữ liệu mô tả các hành động sẽ thực hiện trên các bộ mô tả tệp cụ thể trong quy trình con giữa các bước triển khai thư viện C

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
6 và
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
116. Mục đầu tiên trong mỗi bộ phải là một trong ba chỉ báo loại được liệt kê bên dưới mô tả các phần tử còn lại của bộ

os. POSIX_SPAWN_OPEN

(

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
117, fd, đường dẫn, cờ, chế độ)

Biểu diễn

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
118

os. POSIX_SPAWN_CLOSE

(

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
119, fd)

Biểu diễn

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
120

os. POSIX_SPAWN_DUP2

(

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
121, fd, new_fd)

Biểu diễn

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
122

Các bộ dữ liệu này tương ứng với các lệnh gọi API của thư viện C

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
123,
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
124 và
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
125 được sử dụng để chuẩn bị cho chính lệnh gọi
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
110

Đối số setpgroup sẽ đặt nhóm quy trình của con thành giá trị được chỉ định. Nếu giá trị được chỉ định là 0, ID nhóm quy trình con sẽ được tạo giống với ID quy trình của nó. If the value of setpgroup is not set, the child will inherit the parent’s process group ID. Đối số này tương ứng với cờ

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
127 của thư viện C

Nếu đối số resetids là

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04, nó sẽ đặt lại UID và GID hiệu quả của quy trình con thành UID và GID thực của quy trình gốc. Nếu đối số là
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
92, thì phần tử con sẽ giữ lại UID và GID hiệu lực của phần tử gốc. Trong cả hai trường hợp, nếu các bit quyền set-user-ID và set-group-ID được bật trên tệp thực thi, hiệu ứng của chúng sẽ ghi đè cài đặt của UID và GID hiệu quả. Đối số này tương ứng với cờ
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
130 của thư viện C

Nếu đối số setsid là

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04, nó sẽ tạo ID phiên mới cho
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
132. setsid yêu cầu cờ
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
133 hoặc
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
134. Nếu không, được nâng lên

Đối số setsignmask sẽ đặt mặt nạ tín hiệu thành bộ tín hiệu được chỉ định. Nếu tham số không được sử dụng, thì đứa trẻ sẽ thừa hưởng mặt nạ tín hiệu của cha mẹ. Đối số này tương ứng với cờ

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
136 của thư viện C

Đối số sigdef sẽ đặt lại bố cục của tất cả các tín hiệu trong tập hợp được chỉ định. Đối số này tương ứng với cờ

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
137 của thư viện C

Đối số bộ lập lịch phải là một bộ chứa chính sách bộ lập lịch (tùy chọn) và một thể hiện của các tham số bộ lập lịch. Giá trị của

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
35 ở vị trí của chính sách lập lịch trình cho biết rằng điều đó không được cung cấp. Đối số này là sự kết hợp của thư viện C cờ
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
140 và
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
141

Đưa ra một

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
142 với các đối số
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37,
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
144,
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
061

New in version 3. 8

Unix, not Emscripten, not WASI

os. posix_spawnp(đường dẫn , argv, env, *, file_actions=None, setpgroup=None, resetids=False, setsid=False, setsigmask=(), setsigdef=(), scheduler=None)

Kết thúc API thư viện

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
114 C để sử dụng từ Python

Tương tự ngoại trừ việc hệ thống tìm kiếm tệp thực thi trong danh sách các thư mục được chỉ định bởi biến môi trường

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
027 (theo cách tương tự như đối với
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
149)

Đưa ra một

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
142 với các đối số
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37,
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
144,
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
061

New in version 3. 8

POSIX, không phải Emscripten, không phải WASI

xem tài liệu

os. register_at_fork(* , trước=None, after_in_parent=None, after_in_child=None)

Đăng ký các cuộc gọi để được thực thi khi một quy trình con mới được rẽ nhánh bằng cách sử dụng hoặc các API nhân bản quy trình tương tự. Các tham số là tùy chọn và chỉ từ khóa. Mỗi chỉ định một điểm gọi khác nhau

  • before là một hàm được gọi trước khi forking một tiến trình con

  • after_in_parent is a function called from the parent process after forking a child process

  • after_in_child là một hàm được gọi từ tiến trình con

Các cuộc gọi này chỉ được thực hiện nếu điều khiển dự kiến ​​​​sẽ quay trở lại trình thông dịch Python. Một lần khởi chạy thông thường sẽ không kích hoạt chúng vì đứa trẻ sẽ không vào lại trình thông dịch

Các chức năng đã đăng ký để thực hiện trước khi rẽ nhánh được gọi theo thứ tự đăng ký ngược lại. Các chức năng được đăng ký để thực thi sau khi rẽ nhánh (ở cha hoặc ở con) được gọi theo thứ tự đăng ký

Lưu ý rằng các cuộc gọi

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
6 được thực hiện bởi mã C của bên thứ ba có thể không gọi các chức năng đó, trừ khi nó gọi rõ ràng và

Không có cách nào để hủy đăng ký một chức năng

Unix, not Emscripten, not WASI

New in version 3. 7

os. sinh sản(chế độ , đường dẫn . , ...)os. đẻ trứng(chế độ , đường dẫn . , ... , env)os. spawnlp(chế độ , tệp . , ...)os. spawnlpe(chế độ , tệp . , ... , env)os. spawnv(chế độ , đường dẫn . , args)os.đường sinh sản(chế độ , . , args, env)os.spawnvp(chế độ , tệp . , args)os.spawnvpe(chế độ , tệp, args, env)

Execute the program path in a new process

(Note that the module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using these functions. Đặc biệt kiểm tra phần. )

Nếu chế độ là , hàm này trả về id tiến trình của tiến trình mới; . Trên Windows, process id thực sự sẽ là process handle, vì vậy có thể được sử dụng với chức năng

Lưu ý trên VxWorks, chức năng này không trả về

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
164 khi quy trình mới bị hủy. Thay vào đó, nó làm tăng ngoại lệ OSError

Các biến thể “l” và “v” của các hàm khác nhau về cách truyền đối số dòng lệnh. Các biến thể “l” có lẽ là dễ làm việc nhất nếu số lượng tham số được cố định khi viết mã; . Các biến thể “v” phù hợp khi số lượng tham số thay đổi, với các đối số được chuyển vào danh sách hoặc bộ dưới dạng tham số args. Trong cả hai trường hợp, các đối số của tiến trình con phải bắt đầu bằng tên của lệnh đang chạy

Các biến thể bao gồm chữ “p” thứ hai ở gần cuối (, , và ) sẽ sử dụng biến môi trường

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
027 để định vị tệp chương trình. Khi môi trường đang được thay thế (sử dụng một trong các biến thể, được thảo luận trong đoạn tiếp theo), môi trường mới được sử dụng làm nguồn của biến
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
027. Các biến thể khác, , , và , sẽ không sử dụng biến
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
027 để định vị tệp thực thi;

Đối với , , và (lưu ý rằng tất cả các giá trị này đều kết thúc bằng “e”), tham số env phải là một ánh xạ được sử dụng để xác định các biến môi trường cho quy trình mới (chúng được sử dụng thay cho môi trường của quy trình hiện tại); . Lưu ý rằng các khóa và giá trị trong từ điển env phải là chuỗi;

Như một ví dụ, các cuộc gọi sau đến và là tương đương

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
4

Nâng cao một

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
192 với các đối số
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
38,
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37,
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
060,
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
061

Unix, Windows, not Emscripten, not WASI

, , và không khả dụng trên Windows. và không an toàn cho luồng trên Windows;

Changed in version 3. 6. Accepts a .

os. P_NOWAITos. P_NOWAITO

Các giá trị có thể có cho tham số chế độ đối với họ hàm. Nếu một trong hai giá trị này được cung cấp, các hàm

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
205 sẽ trả về ngay khi quy trình mới được tạo, với id quy trình là giá trị trả về

Unix, Windows

os. P_WAIT

Giá trị có thể cho tham số chế độ đối với họ hàm. Nếu điều này được đưa ra dưới dạng chế độ, các hàm

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
205 sẽ không trả về cho đến khi quy trình mới chạy hoàn tất và sẽ trả về mã thoát của quy trình khi chạy thành công hoặc
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
164 nếu một tín hiệu giết chết quy trình

Unix, Windows

os. P_DETACHos. P_OVERLAY

Các giá trị có thể có cho tham số chế độ đối với họ hàm. Những thứ này ít di động hơn những thứ được liệt kê ở trên. tương tự như , nhưng quy trình mới được tách ra khỏi bảng điều khiển của quy trình gọi. Nếu được sử dụng, quy trình hiện tại sẽ được thay thế;

Windows

os. tệp bắt đầu(đường dẫn[ , operation][, arguments][, cwd][, show_cmd])

Bắt đầu một tệp với ứng dụng được liên kết của nó

Khi thao tác không được chỉ định hoặc

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
214, thao tác này giống như bấm đúp vào tệp trong Windows Explorer hoặc đặt tên tệp làm đối số cho lệnh bắt đầu từ trình bao lệnh tương tác. tệp được mở bằng bất kỳ ứng dụng nào (nếu có) phần mở rộng của nó được liên kết

Khi một thao tác khác được đưa ra, nó phải là một “động từ mệnh lệnh” chỉ định những gì sẽ được thực hiện với tệp. Common verbs documented by Microsoft are

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
215 and
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
216 (to be used on files) as well as
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
217 and
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
218 (to be used on directories)

Khi khởi chạy một ứng dụng, hãy chỉ định các đối số được truyền dưới dạng một chuỗi. Đối số này có thể không có tác dụng khi sử dụng chức năng này để khởi chạy tài liệu

Thư mục làm việc mặc định được kế thừa, nhưng có thể bị ghi đè bởi đối số cwd. Đây phải là một đường dẫn tuyệt đối. Một đường dẫn tương đối sẽ được giải quyết theo đối số này

Sử dụng show_cmd để ghi đè kiểu cửa sổ mặc định. Điều này có ảnh hưởng gì hay không sẽ phụ thuộc vào ứng dụng được khởi chạy. Giá trị là số nguyên như được hỗ trợ bởi hàm Win32

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
219

trả về ngay khi ứng dụng được liên kết được khởi chạy. Không có tùy chọn đợi đóng ứng dụng và không có cách nào để truy xuất trạng thái thoát của ứng dụng. Tham số đường dẫn có liên quan đến thư mục hiện tại hoặc cwd. Nếu bạn muốn sử dụng một đường dẫn tuyệt đối, hãy đảm bảo rằng ký tự đầu tiên không phải là dấu gạch chéo (

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
221) Sử dụng hoặc chức năng để đảm bảo rằng các đường dẫn được mã hóa chính xác cho Win32

Để giảm chi phí khởi động trình thông dịch, chức năng Win32

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
219 không được giải quyết cho đến khi chức năng này được gọi lần đầu tiên. Nếu chức năng không thể được giải quyết, sẽ được nâng lên

Tăng một

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
226 với các đối số
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37,
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
228

Nâng cao một

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
229 với các đối số
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
37,
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
228,
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
232,
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
233,
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
234

Windows

Đã thay đổi trong phiên bản 3. 10. Đã thêm các đối số, đối số cwd và show_cmd cũng như sự kiện kiểm tra

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
229.

os. hệ thống(lệnh)

Thực thi lệnh (một chuỗi) trong một lớp con. Điều này được thực hiện bằng cách gọi chức năng C tiêu chuẩn

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
236 và có những hạn chế tương tự. Thay đổi thành , v.v. không được phản ánh trong môi trường của lệnh được thực thi. Nếu lệnh tạo ra bất kỳ đầu ra nào, nó sẽ được gửi đến luồng đầu ra tiêu chuẩn của trình thông dịch. Tiêu chuẩn C không chỉ định ý nghĩa của giá trị trả về của hàm C, vì vậy giá trị trả về của hàm Python phụ thuộc vào hệ thống

Trên Unix, giá trị trả về là trạng thái thoát của quy trình được mã hóa theo định dạng được chỉ định cho

Trên Windows, giá trị trả về là giá trị được shell hệ thống trả về sau khi chạy lệnh. Shell được cung cấp bởi biến môi trường Windows

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
239. nó thường là cmd. exe, trả về trạng thái thoát của lệnh chạy;

Mô-đun này cung cấp các phương tiện mạnh mẽ hơn để tạo ra các quy trình mới và truy xuất kết quả của chúng; . Xem phần trong tài liệu để biết một số công thức nấu ăn hữu ích

Trên Unix, có thể được sử dụng để chuyển đổi kết quả (trạng thái thoát) thành mã thoát. Trên Windows, kết quả trực tiếp là mã thoát

Đưa ra một

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
243 với lập luận
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
244

Unix, Windows, not Emscripten, not WASI

os. lần()

Trả về thời gian xử lý toàn cầu hiện tại. The return value is an object with five attributes

  • if os.access("myfile", os.R_OK):
        with open("myfile") as fp:
            return fp.read()
    return "some default data"
    
    245 - thời gian của người dùng

  • if os.access("myfile", os.R_OK):
        with open("myfile") as fp:
            return fp.read()
    return "some default data"
    
    246 - giờ hệ thống

  • if os.access("myfile", os.R_OK):
        with open("myfile") as fp:
            return fp.read()
    return "some default data"
    
    247 - thời gian người dùng của tất cả các tiến trình con

  • if os.access("myfile", os.R_OK):
        with open("myfile") as fp:
            return fp.read()
    return "some default data"
    
    248 - thời gian hệ thống của tất cả các tiến trình con

  • if os.access("myfile", os.R_OK):
        with open("myfile") as fp:
            return fp.read()
    return "some default data"
    
    249 - thời gian thực đã trôi qua kể từ một điểm cố định trong quá khứ

Đối với khả năng tương thích ngược, đối tượng này cũng hoạt động giống như một bộ năm bộ chứa

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
245,
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
246,
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
247,
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
248 và
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
249 theo thứ tự đó

Xem trang thủ công Unix times(2) và times(3) trên Unix hoặc GetProcessTimes MSDN trên Windows. Trên Windows, chỉ có

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
245 và
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
246 được biết đến;

Unix, Windows

Changed in version 3. 3. Return type changed from a tuple to a tuple-like object with named attributes.

os. chờ đã()

Đợi quá trình con hoàn thành và trả về một bộ chứa chỉ báo trạng thái thoát và pid của nó. một số 16 bit, có byte thấp là số tín hiệu đã giết quá trình và byte cao là trạng thái thoát (nếu số tín hiệu bằng 0);

Nếu không có đứa trẻ nào có thể chờ đợi, được nuôi dưỡng

có thể được sử dụng để chuyển đổi trạng thái thoát thành mã thoát

Unix, not Emscripten, not WASI

See also

Các hàm

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
259 khác được ghi lại dưới đây có thể được sử dụng để chờ hoàn thành một tiến trình con cụ thể và có nhiều tùy chọn hơn. là cái duy nhất cũng có sẵn trên Windows

os. waitid(idtype , id, options, /)

Đợi quá trình con hoàn thành

idtype có thể là , , hoặc (trên Linux). The interpretation of id depends on it; see their individual descriptions

tùy chọn là tổ hợp cờ OR. Ít nhất một trong số , hoặc được yêu cầu;

Giá trị trả về là một đối tượng đại diện cho dữ liệu chứa trong cấu trúc

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
270 với các thuộc tính sau

  • if os.access("myfile", os.R_OK):
        with open("myfile") as fp:
            return fp.read()
    return "some default data"
    
    271 (ID quy trình)

  • if os.access("myfile", os.R_OK):
        with open("myfile") as fp:
            return fp.read()
    return "some default data"
    
    272 (ID người dùng thực của đứa trẻ)

  • if os.access("myfile", os.R_OK):
        with open("myfile") as fp:
            return fp.read()
    return "some default data"
    
    273 (luôn luôn )

  • if os.access("myfile", os.R_OK):
        with open("myfile") as fp:
            return fp.read()
    return "some default data"
    
    275 (trạng thái thoát hoặc số tín hiệu, tùy thuộc vào
    if os.access("myfile", os.R_OK):
        with open("myfile") as fp:
            return fp.read()
    return "some default data"
    
    276)

  • if os.access("myfile", os.R_OK):
        with open("myfile") as fp:
            return fp.read()
    return "some default data"
    
    276 (xem các giá trị có thể có)

Nếu được chỉ định và không có trẻ em phù hợp trong tiểu bang được yêu cầu,

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
35 được trả lại. Mặt khác, nếu không có con nào phù hợp có thể chờ đợi, sẽ được nuôi

Unix, not Emscripten, not WASI

New in version 3. 3

os. waitpid(pid , tùy chọn, /)

Các chi tiết của chức năng này khác nhau trên Unix và Windows

Trên Unix. Đợi quá trình con được cung cấp bởi id quá trình pid hoàn thành và trả về một bộ chứa id quá trình của nó và chỉ báo trạng thái thoát (được mã hóa thành for ). Ngữ nghĩa của lệnh gọi bị ảnh hưởng bởi giá trị của các tùy chọn số nguyên, giá trị này sẽ là ____0_______83 cho hoạt động bình thường

Nếu pid lớn hơn

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
83, hãy yêu cầu thông tin trạng thái cho quy trình cụ thể đó. Nếu pid là
try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
83, yêu cầu dành cho trạng thái của bất kỳ phần tử con nào trong nhóm quy trình của quy trình hiện tại. Nếu pid là
with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)
32, yêu cầu liên quan đến bất kỳ phần tử con nào của quy trình hiện tại. Nếu pid nhỏ hơn
with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)
32, trạng thái được yêu cầu cho bất kỳ quy trình nào trong nhóm quy trình
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
289 (giá trị tuyệt đối của pid)

options is an OR combination of flags. Nếu nó chứa và không có trẻ em phù hợp trong trạng thái được yêu cầu, thì trả lại

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
291. Mặt khác, nếu không có con nào phù hợp có thể chờ đợi, sẽ được nuôi. Các tùy chọn khác có thể được sử dụng là và

Trên Windows. Đợi hoàn thành một quy trình do pid xử lý quy trình đưa ra và trả về một bộ chứa pid và trạng thái thoát của nó được dịch chuyển sang trái 8 bit (việc dịch chuyển giúp sử dụng chức năng đa nền tảng dễ dàng hơn). Một pid nhỏ hơn hoặc bằng

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()
83 không có ý nghĩa đặc biệt trên Windows và đưa ra một ngoại lệ. Giá trị của các tùy chọn số nguyên không có tác dụng. pid có thể đề cập đến bất kỳ quy trình nào có id được biết, không nhất thiết phải là quy trình con. Các chức năng được gọi với xử lý quy trình phù hợp trả về

có thể được sử dụng để chuyển đổi trạng thái thoát thành mã thoát

Unix, Windows, not Emscripten, not WASI

Changed in version 3. 5. If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising an exception (see PEP 475 for the rationale).

os. chờ3(tùy chọn)

Tương tự với , ngoại trừ không có đối số id quy trình nào được đưa ra và bộ 3 phần tử chứa id quy trình con, chỉ báo trạng thái thoát và thông tin sử dụng tài nguyên được trả về. Tham khảo để biết chi tiết về thông tin sử dụng tài nguyên. Đối số tùy chọn giống như đối số được cung cấp cho và

có thể được sử dụng để chuyển đổi trạng thái thoát thành mã thoát

Unix, not Emscripten, not WASI

os. wait4(pid , tùy chọn)

Tương tự như , ngoại trừ bộ 3 phần tử, chứa id tiến trình con, chỉ báo trạng thái thoát và thông tin sử dụng tài nguyên được trả về. Tham khảo để biết chi tiết về thông tin sử dụng tài nguyên. Các đối số giống như các đối số được cung cấp cho

có thể được sử dụng để chuyển đổi trạng thái thoát thành mã thoát

Unix, not Emscripten, not WASI

os. P_PIDos. P_PGIDos. P_ALLos. P_PIDFD

Đây là những giá trị có thể có cho idtype trong. Chúng ảnh hưởng đến cách hiểu id

  • if os.access("myfile", os.R_OK):
        with open("myfile") as fp:
            return fp.read()
    return "some default data"
    
    261 - đợi đứa trẻ có PID là id

  • if os.access("myfile", os.R_OK):
        with open("myfile") as fp:
            return fp.read()
    return "some default data"
    
    262 - đợi bất kỳ đứa trẻ nào có ID nhóm tiến bộ là id

  • if os.access("myfile", os.R_OK):
        with open("myfile") as fp:
            return fp.read()
    return "some default data"
    
    263 - đợi con nào;

  • if os.access("myfile", os.R_OK):
        with open("myfile") as fp:
            return fp.read()
    return "some default data"
    
    264 - đợi đứa trẻ được xác định bởi id bộ mô tả tệp (bộ mô tả tệp quy trình được tạo bằng )

Unix, not Emscripten, not WASI

Ghi chú

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
264 chỉ khả dụng trên Linux >= 5. 4

New in version 3. 3

Mới trong phiên bản 3. 9. Hằng số

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
264.

os. WCONTINUED

This options flag for , , , and causes child processes to be reported if they have been continued from a job control stop since they were last reported

Unix, not Emscripten, not WASI

os. WEXITED

This options flag for causes child processes that have terminated to be reported

The other

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
323 functions always report children that have terminated, so this option is not available for them

Unix, not Emscripten, not WASI

New in version 3. 3

os. WSTOPPED

This options flag for causes child processes that have been stopped by the delivery of a signal to be reported

This option is not available for the other

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
323 functions

Unix, not Emscripten, not WASI

New in version 3. 3

os. BỎ QUA

Tùy chọn này gắn cờ cho , và khiến các tiến trình con cũng được báo cáo nếu chúng đã bị dừng nhưng trạng thái hiện tại của chúng chưa được báo cáo kể từ khi chúng bị dừng

Tùy chọn này không có sẵn cho

Unix, not Emscripten, not WASI

os. WNOHANG

Cờ tùy chọn này khiến , , và quay lại ngay lập tức nếu không có trạng thái tiến trình con ngay lập tức

Unix, not Emscripten, not WASI

os. CHỜ ĐỢI

Cờ tùy chọn này khiến phần tử con ở trạng thái có thể chờ đợi, do đó có thể sử dụng cuộc gọi

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
259 sau để truy xuất lại thông tin trạng thái phần tử con

This option is not available for the other

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
323 functions

Unix, not Emscripten, not WASI

os. CLD_EXITEDos. CLD_KILLEDos. CLD_DUMPEDos. CLD_TRAPPEDos. CLD_STOPPEDos. CLD_TIẾP TỤC

Đây là những giá trị có thể có cho

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
276 trong kết quả được trả về bởi

Unix, not Emscripten, not WASI

New in version 3. 3

Đã thay đổi trong phiên bản 3. 9. Đã thêm và các giá trị.

os. waitstatus_to_exitcode(trạng thái)

Chuyển đổi trạng thái chờ thành mã thoát

Trên Unix

  • Nếu quy trình đã thoát bình thường (nếu

    if os.access("myfile", os.R_OK):
        with open("myfile") as fp:
            return fp.read()
    return "some default data"
    
    341 là đúng), hãy trả về trạng thái thoát của quy trình (trả về
    if os.access("myfile", os.R_OK):
        with open("myfile") as fp:
            return fp.read()
    return "some default data"
    
    342). kết quả lớn hơn hoặc bằng 0

  • Nếu quá trình bị chấm dứt bởi một tín hiệu (nếu

    if os.access("myfile", os.R_OK):
        with open("myfile") as fp:
            return fp.read()
    return "some default data"
    
    343 là đúng), hãy trả về
    if os.access("myfile", os.R_OK):
        with open("myfile") as fp:
            return fp.read()
    return "some default data"
    
    344 trong đó signum là số của tín hiệu khiến quá trình kết thúc (trả về
    if os.access("myfile", os.R_OK):
        with open("myfile") as fp:
            return fp.read()
    return "some default data"
    
    345). kết quả nhỏ hơn 0

  • Nếu không, nâng cao một

Trên Windows, trạng thái trả về được dịch chuyển sang phải 8 bit

Trên Unix, nếu quá trình đang được theo dõi hoặc nếu được gọi với tùy chọn, trước tiên người gọi phải kiểm tra xem

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
349 có đúng không. Chức năng này không được gọi nếu
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
349 là đúng

See also

, , , , , chức năng

Unix, Windows, not Emscripten, not WASI

Mới trong phiên bản 3. 9

Các hàm sau lấy mã trạng thái quy trình như được trả về bởi , hoặc dưới dạng tham số. Chúng có thể được sử dụng để xác định bố trí của một quá trình

os. WCOREDUMP(trạng thái , /)

Trả lại

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04 nếu kết xuất lõi được tạo cho quy trình, nếu không thì trả lại
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
92

Chức năng này chỉ nên được sử dụng nếu là đúng

Unix, not Emscripten, not WASI

os. ĐANG TIẾP TỤC(trạng thái)

Trả lại

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04 nếu đứa trẻ bị dừng đã được tiếp tục bằng cách chuyển giao (nếu quá trình được tiếp tục từ điểm dừng kiểm soát công việc), nếu không thì trả lại
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
92

xem tùy chọn

Unix, not Emscripten, not WASI

os. ĐÃ NGỪNG(trạng thái)

Trả lại

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04 nếu quá trình bị dừng do gửi tín hiệu, nếu không thì trả lại
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
92

chỉ trả về

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04 nếu cuộc gọi đã được thực hiện bằng cách sử dụng tùy chọn hoặc khi quy trình đang được theo dõi (xem ptrace(2))

Unix, not Emscripten, not WASI

os. WIFSIGNALED(trạng thái)

Trả lại

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04 nếu quá trình bị kết thúc bởi một tín hiệu, nếu không thì trả lại
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
92

Unix, not Emscripten, not WASI

os. WIFEXITED(status)

Trả lại

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
04 nếu quá trình thoát kết thúc bình thường, nghĩa là bằng cách gọi
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
376 hoặc
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
064 hoặc bằng cách quay lại từ
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
014;

Unix, not Emscripten, not WASI

os. WEXITSTATUS(trạng thái)

Trả lại trạng thái thoát quy trình

Chức năng này chỉ nên được sử dụng nếu là đúng

Unix, not Emscripten, not WASI

os. WSTOPSIG(trạng thái)

Trả lại tín hiệu khiến quá trình dừng lại

Chức năng này chỉ nên được sử dụng nếu là đúng

Unix, not Emscripten, not WASI

os. WTERMSIG(trạng thái)

Trả về số lượng tín hiệu khiến quá trình kết thúc

Chức năng này chỉ nên được sử dụng nếu là đúng

Unix, not Emscripten, not WASI

Giao diện bộ hẹn giờ

Các chức năng này kiểm soát cách hệ điều hành phân bổ thời gian CPU cho một quy trình. Chúng chỉ khả dụng trên một số nền tảng Unix. Để biết thêm thông tin chi tiết, hãy tham khảo các trang Unix của bạn

New in version 3. 3

Các chính sách lập lịch trình sau đây được hiển thị nếu chúng được hệ điều hành hỗ trợ

os. SCHED_OTHER

Chính sách lập lịch trình mặc định

os. SCHED_BATCH

Chính sách lập lịch cho các quy trình sử dụng nhiều CPU cố gắng duy trì tính tương tác trên phần còn lại của máy tính

os. SCHED_IDLE

Chính sách lập lịch cho các tác vụ nền có mức độ ưu tiên cực thấp

os. SCHED_SPORADIC

Chính sách lập lịch trình cho các chương trình máy chủ lẻ tẻ

os. SCHED_FIFO

Chính sách lập kế hoạch First In First Out

os. SCHED_RR

Chính sách lập lịch quay vòng

os. SCHED_RESET_ON_FORK

Cờ này có thể được HOẶC với bất kỳ chính sách lập lịch trình nào khác. Khi một quy trình có cờ này đặt rẽ nhánh, chính sách lập lịch và mức độ ưu tiên của quy trình con được đặt lại về mặc định

class os. sched_param(sched_priority)

Lớp này đại diện cho các tham số lập lịch có thể điều chỉnh được sử dụng trong , và. nó là bất biến

Hiện tại, chỉ có một tham số có thể

sched_priority

Mức độ ưu tiên lập lịch cho chính sách lập lịch

os. sched_get_priority_min(chính sách)

Nhận giá trị ưu tiên tối thiểu cho chính sách. chính sách là một trong những hằng số chính sách lập lịch trình ở trên

os. sched_get_priority_max(chính sách)

Nhận giá trị ưu tiên tối đa cho chính sách. chính sách là một trong những hằng số chính sách lập lịch trình ở trên

os. sched_setscheduler(pid , chính sách, param, /)

Đặt chính sách lập lịch cho process với PID pid. Một pid của 0 có nghĩa là quá trình gọi. policy is one of the scheduling policy constants above. param là một ví dụ

os. sched_getscheduler(pid , /)

Trả về chính sách lập lịch trình cho quy trình với PID pid. Một pid của 0 có nghĩa là quá trình gọi. Kết quả là một trong những hằng số chính sách lập lịch ở trên

os. sched_setparam(pid , param, /)

Đặt tham số lập lịch cho process với PID pid. Một pid của 0 có nghĩa là quá trình gọi. param là một ví dụ

os. sched_getparam(pid , /)

Trả về các tham số lập lịch làm ví dụ cho quy trình với PID pid. Một pid của 0 có nghĩa là quá trình gọi

os. sched_rr_get_interval(pid , /)

Trả về lượng tử quay vòng trong vài giây cho quá trình với PID pid. Một pid của 0 có nghĩa là quá trình gọi

os. sched_yield()

Tự nguyện từ bỏ CPU

os. sched_setaffinity(pid , mặt nạ, /)

Hạn chế quy trình với PID pid (hoặc quy trình hiện tại nếu bằng 0) đối với một bộ CPU. mặt nạ là một số nguyên có thể lặp lại đại diện cho tập hợp CPU mà quy trình sẽ bị hạn chế

os. sched_getaffinity(pid , /)

Trả về bộ CPU, quy trình có PID pid (hoặc quy trình hiện tại nếu bằng 0) bị hạn chế đối với

Thông tin hệ thống khác

os. confstr(tên , /)

Trả về các giá trị cấu hình hệ thống có giá trị chuỗi. tên chỉ định giá trị cấu hình để truy xuất; . Một số nền tảng cũng xác định tên bổ sung. Các tên mà hệ điều hành máy chủ biết đến được cung cấp dưới dạng các khóa của từ điển

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
389. Đối với các biến cấu hình không có trong ánh xạ đó, việc chuyển một số nguyên cho tên cũng được chấp nhận

Nếu giá trị cấu hình được chỉ định theo tên không được xác định, thì ______25_______35 được trả về

Nếu tên là một chuỗi và không được biết, được nâng lên. Nếu một giá trị cụ thể cho tên không được hỗ trợ bởi hệ thống máy chủ, ngay cả khi nó được bao gồm trong

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
389, một lỗi sẽ được đưa ra với số lỗi

Unix

os. confstr_names

Các tên ánh xạ từ điển được chấp nhận bởi các giá trị số nguyên được xác định cho các tên đó bởi hệ điều hành máy chủ. Điều này có thể được sử dụng để xác định tập hợp các tên được hệ thống biết đến

Unix

os. số lượng cpu()

Trả về số lượng CPU trong hệ thống. Trả về

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
35 nếu không xác định

Con số này không tương đương với số lượng CPU mà tiến trình hiện tại có thể sử dụng. Số lượng CPU có thể sử dụng có thể thu được bằng

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
397

New in version 3. 4

os. getloadavg()

Trả về số lượng quy trình trong hàng đợi chạy hệ thống được tính trung bình trong 1, 5 và 15 phút qua hoặc tăng nếu không thể đạt được tải trung bình

Unix

os. sysconf(tên , /)

Return integer-valued system configuration values. If the configuration value specified by name isn’t defined,

with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)
32 is returned. The comments regarding the name parameter for apply here as well; the dictionary that provides information on the known names is given by
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
401

Unix

os. sysconf_names

Các tên ánh xạ từ điển được chấp nhận bởi các giá trị số nguyên được xác định cho các tên đó bởi hệ điều hành máy chủ. Điều này có thể được sử dụng để xác định tập hợp các tên được hệ thống biết đến

Unix

Changed in version 3. 11. Add

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
403 name.

Các giá trị dữ liệu sau đây được sử dụng để hỗ trợ các thao tác thao tác trên đường dẫn. These are defined for all platforms

Higher-level operations on pathnames are defined in the module

os. sữa chua

The constant string used by the operating system to refer to the current directory. Đây là

os.stat in os.supports_dir_fd
14 cho Windows và POSIX. Cũng có sẵn thông qua

os. xin lỗi

The constant string used by the operating system to refer to the parent directory. Đây là

os.stat in os.supports_dir_fd
15 cho Windows và POSIX. Also available via

os. sep

The character used by the operating system to separate pathname components. Đây là

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
221 cho POSIX và
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
410 cho Windows. Note that knowing this is not sufficient to be able to parse or concatenate pathnames — use and — but it is occasionally useful. Also available via

os. altsep

Một ký tự thay thế được hệ điều hành sử dụng để phân tách các thành phần tên đường dẫn hoặc

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
35 nếu chỉ tồn tại một ký tự phân cách. This is set to
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
221 on Windows systems where
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
416 is a backslash. Also available via

os. extsep

The character which separates the base filename from the extension; for example, the

os.stat in os.supports_dir_fd
14 in
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
419. Also available via

os. pathsep

The character conventionally used by the operating system to separate search path components (as in

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
027), such as
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
422 for POSIX or
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
423 for Windows. Also available via

os. defpath

Đường dẫn tìm kiếm mặc định được sử dụng bởi và nếu môi trường không có khóa

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
427. Also available via

os. dòng

The string used to separate (or, rather, terminate) lines on the current platform. Đây có thể là một ký tự đơn, chẳng hạn như

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
429 cho POSIX hoặc nhiều ký tự, chẳng hạn như
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
430 cho Windows. Do not use os. linesep làm dấu kết thúc dòng khi ghi tệp được mở ở chế độ văn bản (mặc định);

os. devnull

The file path of the null device. Ví dụ.

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
432 cho POSIX,
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
433 cho Windows. Also available via

os. RTLD_LAZYos. RTLD_NOWos. RTLD_GLOBALos. RTLD_LOCALos. RTLD_NODELETEos. RTLD_NOLOADos. RTLD_DEEPBIND

Cờ để sử dụng với các chức năng và. Xem trang thủ công Unix dlopen(3) để biết ý nghĩa của các cờ khác nhau

New in version 3. 3

Số ngẫu nhiên

os. getrandom(size , flags=0)

Lên đến kích thước byte ngẫu nhiên. Hàm có thể trả về ít byte hơn yêu cầu

Các byte này có thể được sử dụng để khởi tạo các trình tạo số ngẫu nhiên trong không gian người dùng hoặc cho các mục đích mã hóa

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
437 dựa vào entropy được thu thập từ trình điều khiển thiết bị và các nguồn tiếng ồn môi trường khác. Unnecessarily reading large quantities of data will have a negative impact on other users of the
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
438 and
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
439 devices

Đối số flags là một mặt nạ bit có thể chứa 0 hoặc nhiều giá trị sau ORed cùng nhau. Và

Xem thêm trang thủ công Linux getrandom()

Linux >= 3. 17

New in version 3. 6

os. độ ngẫu nhiên(kích thước , /)

Return a bytestring of size random bytes suitable for cryptographic use

Hàm này trả về các byte ngẫu nhiên từ nguồn ngẫu nhiên dành riêng cho hệ điều hành. Dữ liệu được trả về phải đủ khó đoán đối với các ứng dụng mật mã, mặc dù chất lượng chính xác của nó phụ thuộc vào việc triển khai hệ điều hành

On Linux, if the

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
437 syscall is available, it is used in blocking mode. chặn cho đến khi nhóm entropy urandom của hệ thống được khởi tạo (128 bit entropy được kernel thu thập). Xem PEP 524 để biết lý do. Trên Linux, chức năng này có thể được sử dụng để lấy các byte ngẫu nhiên ở chế độ không chặn (sử dụng cờ) hoặc để thăm dò cho đến khi nhóm entropy urandom của hệ thống được khởi tạo

On a Unix-like system, random bytes are read from the

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
439 device. If the
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
439 device is not available or not readable, the exception is raised

On Windows, it will use

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
448

See also

Mô-đun cung cấp các chức năng cấp cao hơn. Để biết giao diện dễ sử dụng cho trình tạo số ngẫu nhiên do nền tảng của bạn cung cấp, vui lòng xem

Changed in version 3. 6. 0. Trên Linux,

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
437 hiện được sử dụng ở chế độ chặn để tăng tính bảo mật.

Changed in version 3. 5. 2. Trên Linux, nếu khối syscall

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
437 (nhóm entropy urandom chưa được khởi tạo), hãy quay lại đọc
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
439.

Đã thay đổi trong phiên bản 3. 5. On Linux 3. 17 trở lên, syscall

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
437 hiện được sử dụng khi khả dụng. On OpenBSD 5. 6 và mới hơn, chức năng C
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
455 hiện được sử dụng. Các chức năng này tránh việc sử dụng bộ mô tả tệp nội bộ.

Changed in version 3. 11. On Windows,

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
448 is used instead of
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
457 which is deprecated.

os. GRND_NONBLOCK

By default, when reading from

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
438, blocks if no random bytes are available, and when reading from
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
439, it blocks if the entropy pool has not yet been initialized

Nếu cờ được đặt, thì không chặn trong những trường hợp này mà thay vào đó, nó sẽ tăng ngay lập tức

New in version 3. 6

os. GRND_RANDOM

If this bit is set, then random bytes are drawn from the

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
438 pool instead of the
if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"
439 pool

Làm cách nào để sử dụng biến đầu vào cho tên tệp trong Python?

inputFileName = input("Nhập tên của tập tin đầu vào. ") inputFile = open(inputFileName, "r") print("Đang mở tệp", inputFileName, " để đọc. ") 1. Mở tệp và liên kết tệp với một biến tệp (tệp bị “khóa” để ghi).

Có thể tạo tệp văn bản bằng Python không?

Python cung cấp các chức năng sẵn có để tạo, ghi và đọc tệp . Có hai loại tệp có thể được xử lý trong python, tệp văn bản bình thường và tệp nhị phân (được viết bằng ngôn ngữ nhị phân, 0 và 1).