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. 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 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
exception os. lỗiBí danh cho ngoại lệ tích hợp
os. nameTê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
Xem thêm
có độ chi tiết tốt hơn. cung cấp thông tin phiên bản phụ thuộc vào hệ thống
Mô-đun này cung cấp các kiểm tra chi tiết về danh tính của hệ thống
Tên tệp, đối số dòng lệnh và biến môi trường
Trong Python, tên tệp, đối số dòng lệnh và biến môi trường được biểu diễn bằng kiểu chuỗi. Trên một số hệ thống, việc giải mã các chuỗi này đến và từ byte là cần thiết trước khi chuyển chúng đến hệ điều hành. Python sử dụng để thực hiện chuyển đổi này [xem ]
Được cấu hình khi khởi động Python bằng hàm
>>> 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 2642. xem và các thành viên của
Đã thay đổi trong phiên bản 3. 1. Trên một số hệ thống, quá trình chuyển đổi bằng mã hóa hệ thống tệp có thể không thành công. Trong trường hợp này, Python sử dụng , có nghĩa là các byte không thể giải mã được thay thế bằng ký tự Unicode U+DCxx khi giải mã và chúng lại được dịch sang byte gốc khi mã hóa.
Phải đảm bảo giải mã thành công tất cả các byte dưới 128. Nếu mã hóa hệ thống tệp không cung cấp bảo đảm này, các chức năng API có thể tăng
Xem thêm
Chế độ Python UTF-8
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
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
8returns
>>> 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 useos.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
Note that the standard stream settings in UTF-8 mode can be overridden by [just as they can be in the default locale-aware mode]
As a consequence of the changes in those lower level APIs, other higher level APIs also exhibit different default behaviours
Command line arguments, environment variables and filenames are decoded to text using the UTF-8 encoding
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_ids7 or
os.access in os.supports_effective_ids8 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 2642 function]
It can be enabled or disabled using the command line option and the environment variable
Nếu biến môi trường hoàn toàn không được đặt, thì trình thông dịch sẽ mặc định sử dụng cài đặt ngôn ngữ hiện tại, trừ khi ngôn ngữ hiện tại được xác định là ngôn ngữ dựa trên ASCII kế thừa [như được mô tả cho ] và tính năng cưỡng chế ngôn ngữ bị vô hiệu hóa hoặc không thành công. 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
Xem thêm
PEP 686Python 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. environA object where keys and values are strings that represent the process environment. For example,
os.chdir in os.supports_fd5 is the pathname of your home directory [on some platforms], and is equivalent to
os.chdir in os.supports_fd6 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_fd8. 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_symlinks3 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_symlinks8 may cause memory leaks. Refer to the system documentation for
os.stat in os.supports_follow_symlinks1
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 directories2 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 directories3 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 directories4] 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 directories5] 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
New in version 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 directories4] 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 directories5] operators. os. chdir[path]os. fchdir[fd]os. getcwd[]
These functions are described in
os. fsencode[filename]Encode filename to the ; return unchanged
is the reverse function
New in version 3. 2
Changed in version 3. 6. Support added to accept objects implementing the interface.
os. fsdecode[filename]Decode the filename from the ; return unchanged
is the reverse function
New in version 3. 2
Changed in version 3. 6. Support added to accept objects implementing the interface.
os. fspath[path]Return the file system representation of the path
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
class os. PathLikeAn 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_symlinks3 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
New in version 3. 2
os. get_exec_path[env=None]Trả về danh sách các thư mục sẽ được tìm kiếm cho một tệp thực thi được đặt tên, tương tự như trình bao, khi khởi chạy một quy trình. env, khi được chỉ định, phải là một từ điển biến môi trường để tra cứu PATH trong. Theo mặc định, khi env là
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"35, được sử dụng
New in version 3. 2
os. getegid[]Trả về id nhóm hiệu quả của quy trình hiện tại. 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_USERParameters 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
New in version 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
New in version 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 , /]Gọi hệ thống initgroups[] để khởi tạo danh sách truy cập nhóm với tất cả các nhóm mà tên người dùng được chỉ định là thành viên, cộng với id nhóm được chỉ định
Unix, not Emscripten, not WASI
New in version 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_symlinks8 may cause memory leaks. Refer to the system documentation for
os.stat in os.supports_follow_symlinks1
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]. Xem hướng dẫn sử dụng Unix để biết ngữ nghĩa
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. ưu tiên là một giá trị trong phạm vi -20 đến 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 , /]Đặt id nhóm thực và hiệu quả của quy trình hiện tại
Unix, not Emscripten, not WASI
os. setresgid[rgid , egid, sgid, /]Đặt id nhóm thực, hiệu quả và đã lưu của quy trình hiện tại
Unix, not Emscripten, not WASI
New in version 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
New in version 3. 2
os. setreuid[ruid , euid, /]Đặt id người dùng thực và hiệu quả của quy trình hiện tại
Unix, not Emscripten, not WASI
os. getsid[pid , /]Gọi cuộc gọi hệ thống
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"86. Xem hướng dẫn sử dụng Unix để biết ngữ nghĩa
Unix, not Emscripten, not WASI
os. setsid[]Gọi cuộc gọi hệ thống
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"87. Xem hướng dẫn sử dụng Unix để biết ngữ nghĩa
Unix, not Emscripten, not WASI
os. setuid[uid , /]Đặt id người dùng của quy trình hiện tại
Unix, not Emscripten, not WASI
os. lỗi[mã , /]Trả về thông báo lỗi tương ứng với mã lỗi trong code. Trên các nền tảng mà
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"88 trả về
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"89 khi được cung cấp một số lỗi không xác định, được nâng lênos. supports_bytes_environ
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"04 nếu loại hệ điều hành gốc của môi trường là byte [ví dụ:.
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"92 on Windows]
New in version 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 nameif 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 releaseif os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"
96 - operating system versionif 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. Ví dụ: đầu vào tiêu chuẩn thường là bộ mô tả tệp 0, đầu ra tiêu chuẩn là 1 và lỗi tiêu chuẩn là 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: passos. 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
Trên Unix, nếu được bật, hãy trả về
try: fp = open["myfile"] except PermissionError: return "some default data" else: with fp: return fp.read[]31 thay vì mã hóa thiết bị
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. The new file descriptor is
On Windows, when duplicating a standard stream [0. stdin, 1. stdout, 2. stderr], the new file descriptor is
not WASI
Changed in version 3. 4. The new file descriptor is now non-inheritable.
os. dup2[fd , fd2 , inheritable=True]Duplicate file descriptor fd to fd2, closing the latter first if necessary. Return 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
not WASI
Changed in version 3. 4. Add the optional inheritable parameter.
Changed in version 3. 7. Return fd2 on success. Previously,
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"35 was always returned. os. fchmod[fd , mode]
Change the mode of the file given by fd to the numeric mode. See the docs for for possible values of mode. 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[]35
Raises an
try: fp = open["myfile"] except PermissionError: return "some default data" else: with fp: return fp.read[]36 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
Unix
The function is limited on Emscripten and WASI, see for more information
os. fchown[fd , uid , gid]Change the owner and group id of the file given by fd to the numeric uid and gid. To leave one of the ids unchanged, set it to -1. See . 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[]41
Raises an
try: fp = open["myfile"] except PermissionError: return "some default data" else: with fp: return fp.read[]42 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[]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
The function is limited on Emscripten and WASI, see for more information
os. fdatasync[fd]Force write of file with filedescriptor fd to disk. Does not force update of metadata
Unix
Ghi chú
This function is not available on 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
Xem thêm
The function
os. fstatvfs[fd , /]Return information about the filesystem containing the file associated with file descriptor fd, like . 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[]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
The function is limited on Emscripten and WASI, see for more information
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"92os. 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_TESTFlags 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. hoặc
try: fp = open["myfile"] except PermissionError: return "some default data" else: with fp: return fp.read[]83 để đặt vị trí so với phần đầu của tệp; . Trả lại vị trí con trỏ mới theo byte, bắt đầu từ đầuos. 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. Some operating systems could support additional values, like
try: fp = open["myfile"] except PermissionError: return "some default data" else: with fp: return fp.read[]89 or
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 directories4. 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 Windowsos. 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_CLOEXECThe 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_TEXTThe above constants are only available on Windows
os. O_EVTONLYos. O_FSYNCos. O_SYMLINKos. O_NOFOLLOW_ANYThe 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_EXLOCKThe 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. ống2[cờ , /]Create a pipe with flags set atomically. cờ có thể được xây dựng bằng ORing với nhau một hoặc nhiều giá trị này. , . Trả về một cặp mô tả tệp
with os.scandir[path] as it: for entry in it: if not entry.name.startswith['.'] and entry.is_file[]: print[entry.name]15 tương ứng có thể sử dụng để đọc và viết
Unix, not Emscripten, not WASI
New in version 3. 3
os. posix_fallocate[fd , offset, len, /]Đảm bảo phân bổ đủ dung lượng đĩa cho tệp được chỉ định bởi fd bắt đầu từ offset và tiếp tục cho len byte
Unix, không phải Emscripten
New in version 3. 3
os. posix_fadvise[fd , offset, len, advice, /]Thông báo ý định truy cập dữ liệu theo một mẫu cụ thể, do đó cho phép hạt nhân thực hiện tối ưu hóa. Lời khuyên áp dụng cho vùng của tệp được chỉ định bởi fd bắt đầu từ offset và tiếp tục cho len byte. 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_DONTNEEDFlags that can be used in advice in that specify the access pattern that is likely to be used
Unix
New in version 3. 3
os. pread[fd , n , offset , /]Read at most n bytes from file descriptor fd at a position of offset, leaving the file offset unchanged
Return a bytestring containing the bytes read. If the end of the file referred to by fd has been reached, an empty bytes object is returned
Unix
New in version 3. 3
os. preadv[fd , buffers , offset , flags=0 , /]Read from a file descriptor fd at a position of offset into mutable buffers, leaving the file offset unchanged. 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
The flags argument contains a bitwise OR of zero or more of the following flags
Return the total number of bytes actually read which can be less than the total capacity of all the objects
The operating system may set a limit [ value
with os.scandir[path] as it: for entry in it: if not entry.name.startswith['.'] and entry.is_file[]: print[entry.name]29] on the number of buffers that can be used
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Đừng đợi dữ liệu không có sẵn ngay lập tức. Nếu cờ này được chỉ định, lệnh gọi hệ thống sẽ trả về ngay lập tức nếu nó phải đọc dữ liệu từ bộ lưu trữ dự phòng hoặc chờ khóa
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_HIPRIHigh priority read/write. Cho phép các hệ thống tệp dựa trên khối sử dụng tính năng bỏ phiếu của thiết bị, mang lại độ trễ thấp hơn nhưng có thể sử dụng các tài nguyên bổ sung
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
The flags argument contains a bitwise OR of zero or more of the following flags
Return the total number of bytes actually written
The operating system may set a limit [ value
with os.scandir[path] as it: for entry in it: if not entry.name.startswith['.'] and entry.is_file[]: print[entry.name]29] on the number of buffers that can be used
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_DSYNCProvide 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_SYNCProvide 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_APPENDProvide 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
Return a bytestring containing the bytes read. If the end of the file referred to by fd has been reached, an empty bytes object is returned
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
The function is limited on Emscripten and WASI, see for more information
New in version 3. 5
os. SF_NODISKIOos. SF_MNOWAITos. SF_SYNCParameters to the function, if the implementation supports them
Unix, not Emscripten, not WASI
New in version 3. 3
os. SF_NOCACHEParameter 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. 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
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_MORENew 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
Return the total number of bytes actually read which can be less than the total capacity of all the objects
The operating system may set a limit [ value
with os.scandir[path] as it: for entry in it: if not entry.name.startswith['.'] and entry.is_file[]: print[entry.name]29] on the number of buffers that can be used
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. bộ đệm phải là một chuỗi các. 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
The operating system may set a limit [ value
with os.scandir[path] as it: for entry in it: if not entry.name.startswith['.'] and entry.is_file[]: print[entry.name]29] on the number of buffers that can be used
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
là chức năng cấp cao thường được sử dụng,
with os.scandir[path] as it: for entry in it: if not entry.name.startswith['.'] and entry.is_file[]: print[entry.name]96 là triển khai cấp thấp
Unix, Windows
class os. terminal_sizeA 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 sizecolumns
Width of the terminal window in characters
linesHeight 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 modifiedos. 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. Nếu follow_symlinks là
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"
92 và phần tử cuối cùng của đường dẫn hoạt động trên đó là một liên kết tượng trưng, thì hàm sẽ hoạt động trên chính liên kết tượng trưng đó chứ không phải tệp được chỉ ra bởi liên kết. [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 . Nếu nó không có sẵn, sử dụng nó sẽ tăng
Use the real uid/gid to test for access to path. Lưu ý rằng hầu hết các hoạt động sẽ sử dụng uid/gid hiệu quả, do đó, quy trình này có thể được sử dụng trong môi trường suid/sgid để kiểm tra xem người dùng đang gọi có quyền truy cập được chỉ định vào đường dẫn hay không. 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
This function can support specifying and
Nếu effect_ids là
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"04, sẽ thực hiện kiểm tra quyền truy cập bằng cách sử dụng uid/gid hiệu dụng thay vì uid/gid thực. 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ú
Using to check if a user is authorized to e. g. open a file before actually doing so using creates a security hole, because the user might exploit the short time interval between checking and opening the file to manipulate it. It’s preferable to use techniques. For example
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"
is better written as
try: fp = open["myfile"] except PermissionError: return "some default data" else: with fp: return fp.read[]
Ghi chú
I/O operations may fail even when indicates that they would succeed, particularly for operations on network filesystems which may have permissions semantics beyond the usual POSIX permission-bit model
Changed in version 3. 3. Added the dir_fd, effective_ids, and follow_symlinks parameters.
Changed in version 3. 6. Accepts a .
os. F_OKos. R_OKos. W_OKos. X_OKValues 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 26438 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 26453 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 26462 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 26461 constants or a corresponding integer value]. All other bits are ignored
The function is limited on Emscripten and WASI, see for more information
Raises an
try: fp = open["myfile"] except PermissionError: return "some default data" else: with fp: return fp.read[]36 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. 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. Để giữ nguyên một trong các id, hãy đặt nó thành -1
This function can support , and
See for a higher-level function that accepts names in addition to numeric ids
Raises an
try: fp = open["myfile"] except PermissionError: return "some default data" else: with fp: return fp.read[]42 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[]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
The function is limited on Emscripten and WASI, see for more information
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 26489
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 26438 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 26493
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 26453 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 26498
Raises an
try: fp = open["myfile"] except PermissionError: return "some default data" else: with fp: return fp.read[]36 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
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_fd03
Raises an
try: fp = open["myfile"] except PermissionError: return "some default data" else: with fp: return fp.read[]42 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[]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_fd09 with arguments
os.stat in os.supports_dir_fd10,
os.stat in os.supports_dir_fd11,
os.stat in os.supports_dir_fd12,
os.stat in os.supports_dir_fd13
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[đường dẫn='. ']Trả về danh sách chứa tên của các mục trong thư mục được cung cấp bởi đường dẫn. The list is in arbitrary order, and does not include the special entries
os.stat in os.supports_dir_fd14 and
os.stat in os.supports_dir_fd15 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
con đường có thể là một. 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 directories7 [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 directories7; 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
Đưa ra một
os.stat in os.supports_dir_fd20 với lập luận
try: fp = open["myfile"] except PermissionError: return "some default data" else: with fp: return fp.read[]37
Ghi chú
Để mã hóa tên tệp
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"10 thà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 directories7, hãy sử dụng
Xem thêm
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[path , * , dir_fd=None]Perform the equivalent of an
os.stat in os.supports_dir_fd26 system call on the given path. Similar to , but does not follow symbolic links. 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_fd30
This function can also support
Xem thêm
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_fd38 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. To set the file permission bits of any newly created parent directories you can set the umask before invoking . 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ú
sẽ trở nên bối rối nếu các phần tử đường dẫn cần tạo bao gồm [ví dụ:. “. ” on UNIX systems]
This function handles UNC paths correctly
Raises an
os.stat in os.supports_dir_fd38 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_fd57,
os.stat in os.supports_dir_fd58,
os.stat in os.supports_dir_fd59, and
os.stat in os.supports_dir_fd60 [those constants are available in ]. For
os.stat in os.supports_dir_fd58 and
os.stat in os.supports_dir_fd59, 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_fd65 or
os.stat in os.supports_dir_fd66 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 26440]os. minor[device , /]
Extract the device minor number from a raw device number [usually the
os.stat in os.supports_dir_fd65 or
os.stat in os.supports_dir_fd66 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 26440]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_namesCác tên ánh xạ từ điển được chấp nhận bởi và tớ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ủ. 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_fd78
If the path is a string object [directly or indirectly through a interface], the result will also be a string object, and the call may raise a UnicodeDecodeError. If the path is a bytes object [direct or indirectly], the result will be a bytes object
This function can also support
When trying to resolve a path that may contain links, use to properly handle recursion and platform differences
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.
Changed in version 3. 6. Chấp nhận trên 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_fd81 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. Use to remove directories. 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_fd86 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 .
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_fd91 will first remove the directory
os.stat in os.supports_dir_fd92, and then remove
os.stat in os.supports_dir_fd93 and
os.stat in os.supports_dir_fd94 if they are empty. Raises if the leaf directory could not be successfully removed
Raises an
os.stat in os.supports_dir_fd86 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_ids06 with arguments
os.stat in os.supports_dir_fd10,
os.stat in os.supports_dir_fd11,
os.stat in os.supports_dir_fd12,
os.stat in os.supports_dir_fd13
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ú
Chức năng này có thể không thành công với cấu trúc thư mục mới được tạo nếu bạn thiếu các quyền cần thiết để xóa thư mục lá hoặc tệp
Raises an
os.access in os.supports_effective_ids06 with arguments
os.stat in os.supports_dir_fd10,
os.stat in os.supports_dir_fd11,
os.stat in os.supports_dir_fd12,
os.stat in os.supports_dir_fd13
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_ids06 with arguments
os.stat in os.supports_dir_fd10,
os.stat in os.supports_dir_fd11,
os.stat in os.supports_dir_fd12,
os.stat in os.supports_dir_fd13
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_ids27 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[path='. ']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_fd14 and
os.stat in os.supports_dir_fd15 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 directories7 [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 directories7; 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_ids47 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_fd14. The
os.access in os.supports_effective_ids53 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. DirEntryObject 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_fd26 system call is made, the
os.access in os.supports_effective_ids30 object will cache the result
os.access in os.supports_effective_ids30 instances are not intended to be stored in long-lived data structures; if you know the file metadata has changed or if a long time has elapsed since calling , call
os.access in os.supports_effective_ids65 to fetch up-to-date information
Because the
os.access in os.supports_effective_ids30 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_ids30 methods and handle as appropriate
Để có thể sử dụng trực tiếp dưới dạng ,
os.access in os.supports_effective_ids30 triển khai giao diện
Attributes and methods on a
os.access in os.supports_effective_ids30 instance are as followsname
Tên tệp cơ sở của mục nhập, liên quan đến đối số đường dẫn
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 directories7 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 directories7 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 filenamespath
The entry’s full path name. equivalent to
os.access in os.supports_effective_ids80 where scandir_path is the path argument. The path is only absolute if the path argument was absolute. 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 directories7 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 directories7 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 filenamesinode[]
Return the inode number of the entry
Kết quả được lưu trữ trên đối tượng
os.access in os.supports_effective_ids30. Sử dụng
os.access in os.supports_effective_ids93 để lấy thông tin cập nhật
Trong cuộc gọi đầu tiên, chưa được lưu trong bộ đệm, một cuộc gọi hệ thống được yêu cầu trên Windows nhưng không phải trên Unix
is_dir[* , follow_symlinks=True]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 mục nhập này là một thư mục hoặc một liên kết tượng trưng trỏ đến một thư mục;
Nếu follow_symlinks là
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 mục nhập này là một thư mục [không theo dõi các liên kết tượng trưng];
Kết quả được lưu vào bộ đệm trên đối tượng
os.access in os.supports_effective_ids30, với bộ đệm riêng cho các liên kết tượng trưng theo dõi
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"04 và
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"92. Gọi cùng với để lấy thông tin cập nhật
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. Cụ thể, đối với các liên kết không phải là liên kết tượng trưng, cả Windows hoặc Unix đều không yêu cầu lệnh gọi hệ thống, ngoại trừ trên một số hệ thống tệp Unix nhất định, chẳng hạn như hệ thống tệp mạng, trả về
os.chdir in os.supports_fd04. Nếu mục nhập là một liên kết tượng trưng, thì một lệnh gọi hệ thống sẽ được yêu cầu thực hiện theo liên kết tượng trưng trừ khi follow_symlinks là
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"92
Phương pháp này có thể tăng, chẳng hạn như, nhưng bị bắt và không tăng
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_ids30 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_ids30 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_fd04
Phương pháp này có thể tăng, chẳng hạn như, nhưng bị bắt và không tăng
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_fd25 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_fd27,
os.stat in os.supports_dir_fd65 and
os.chdir in os.supports_fd29 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_ids30 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_ids30 and of . In particular, the
os.access in os.supports_effective_ids42 attribute has the same meaning, as do the
os.access in os.supports_effective_ids37,
os.access in os.supports_effective_ids38,
os.chdir in os.supports_fd41 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. chỉ số[đường dẫn , *, 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_fd25, or use
This function can support and
On Windows, passing
os.chdir in os.supports_fd25 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
Xem thêm
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_fd25 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_fd25 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 26440 structure. It is used for the result of , and
Attributes
st_modeFile mode. file type and file mode bits [permissions]
st_inoPlatform dependent, but if non-zero, uniquely identifies the file for a given value of
os.stat in os.supports_dir_fd65. Typically
the inode number on Unix,
the file index on Windows
Identifier of the device on which this file resides
st_nlinkNumber of hard links
st_uidUser identifier of the file owner
st_gidGroup identifier of the file owner
st_sizeSize 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_atimeTime of most recent access expressed in seconds
st_mtimeTime of most recent content modification expressed in seconds
st_ctimePlatform dependent
the time of most recent metadata change on Unix,
the time of creation on Windows, expressed in seconds
Time of most recent access expressed in nanoseconds as an integer
st_mtime_nsTime of most recent content modification expressed in nanoseconds as an integer
st_ctime_nsPlatform dependent
the time of most recent metadata change on Unix,
the time of creation on Windows, expressed in nanoseconds as an integer
Ghi chú
Ý nghĩa và độ phân giải chính xác của các thuộc tính , , và phụ thuộc vào hệ điều hành và hệ thống tệp. Ví dụ: trên hệ thống Windows sử dụng hệ thống tệp FAT hoặc FAT32, có độ phân giải 2 giây và chỉ có độ phân giải 1 ngày. Xem tài liệu hệ điều hành của bạn để biết chi tiết
Tương tự, mặc dù , , và luôn được biểu thị bằng nano giây, nhiều hệ thống không cung cấp độ chính xác nano giây. 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. Nếu bạn cần dấu thời gian chính xác, bạn phải luôn sử dụng , và
Trên một số hệ thống Unix [chẳng hạn như Linux], các thuộc tính sau đây cũng có thể khả dụng
st_blocksSố khối 512 byte được phân bổ cho tệp. Giá trị này có thể nhỏ hơn /512 khi tệp có lỗ hổng
st_blksizeKích thước khối "ưa thích" cho I/O hệ thống tệp hiệu quả. 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_rdevLoại thiết bị nếu là thiết bị inode
st_flagsCờ do người dùng xác định cho tệp
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_gensố thế hệ tập tin
st_birthtimeThờ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_fstypeChuỗ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_rsizeKích thước thật của tập tin
st_creatorNgười tạo tập tin
st_typeLoạ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_attributesThuộc tính tệp Windows. Thành viên
os.chdir in os.supports_fd77 của cấu trúc
os.chdir in os.supports_fd78 được trả về bởi
os.chdir in os.supports_fd79. Xem hằng số
os.chdir in os.supports_fd80 trong mô-đunst_reparse_tag
Khi đã đặt
os.chdir in os.supports_fd83, 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_fd84 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 26440. [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 26440, 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_symlinks09,
os.stat in os.supports_follow_symlinks10 hoặc
os.stat in os.supports_follow_symlinks11 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_symlinks13, cụ thể là.
os.stat in os.supports_follow_symlinks14,
os.stat in os.supports_follow_symlinks15,
os.stat in os.supports_follow_symlinks16,
os.stat in os.supports_follow_symlinks17,
os.stat in os.supports_follow_symlinks18,
os.stat in os.supports_follow_symlinks19,
os.stat in os.supports_follow_symlinks20,
os.stat in os.supports_follow_symlinks21,
os.stat in os.supports_follow_symlinks22,
os.stat in os.supports_follow_symlinks23,
os.stat in os.supports_follow_symlinks24
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_symlinks22. if
os.stat in os.supports_follow_symlinks26 is set, the filesystem is mounted read-only, and if
os.stat in os.supports_follow_symlinks27 is set, the semantics of setuid/setgid bits are disabled or not supported
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_symlinks28 [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_symlinks29 [không cho phép thực thi chương trình],
os.stat in os.supports_follow_symlinks30 [ghi được đồng bộ hóa cùng một lúc],
os.stat in os.supports_follow_symlinks31 [cho phép khóa bắt buộc trên FS],
os.stat in os.supports_follow_symlinks32 [ghi trên tệp/thư mục/liên kết tượng trưng],
os.stat in os.supports_follow_symlinks33
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_symlinks26 và
os.stat in os.supports_follow_symlinks27 đã đượ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_symlinks28,
os.stat in os.supports_follow_symlinks29,
os.stat in os.supports_follow_symlinks30,
os.stat in os.supports_follow_symlinks31,
os.stat in os.supports_follow_symlinks32,
os.stat in os.supports_follow_symlinks33,
os.stat in os.supports_follow_symlinks34,
os.stat in os.supports_follow_symlinks35,
os.stat in os.supports_follow_symlinks36 và
os.stat in os.supports_follow_symlinks37 đã được thêm vào.
Changed in version 3. 6. Accepts a .
Mới trong phiên bản 3. 7. Đã thêm
os.stat in os.supports_follow_symlinks24. 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ộ. [Chỉ định
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"35 cho dir_fd 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 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_symlinks54 trên
os.stat in os.supports_follow_symlinks55. As an example, this expression evaluates to
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"04 if accepts open file descriptors for dir_fd on the local platform
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_idsMộ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_symlinks65 trên nền tảng cục bộ
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_fdMộ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_symlinks54 trên
os.stat in os.supports_follow_symlinks69. 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_symlinksMộ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ợ. For consistency’s sake, functions that may support follow_symlinks always allow specifying the parameter, but will throw an exception if the functionality is used when it’s not locally available. [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_symlinks54 trên
os.stat in os.supports_follow_symlinks78. 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_fd25 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_symlinks84 với các đối số
os.stat in os.supports_dir_fd10,
os.stat in os.supports_dir_fd11,
try: fp = open["myfile"] except PermissionError: return "some default data" else: with fp: return fp.read[]39
Unix, Windows
The function is limited on Emscripten and WASI, see for more information
Changed in version 3. 2. Added support for Windows 6. 0 [Vista] symbolic links.
Mới trong phiên bản 3. 3. Đã thêm đối số dir_fd và hiện cho phép target_is_directory trên các nền tảng không phải Windows.
Changed in version 3. 6. Accepts a for src and dst.
Đã thay đổi trong phiên bản 3. 8. Added support for unelevated symlinks on Windows with Developer Mode.
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_fd86 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, lần và ns. Chúng chỉ định thời gian được đặt trên đường dẫn và được sử dụng như sau
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ỉ địnhimport 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 directories07 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 directories09,
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 directories10,
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 directories12
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_fd14 và
os.stat in os.supports_dir_fd15]. 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 directories15. Danh sách có được sắp xếp hay không tùy thuộc vào hệ thống tệp. Nếu một tệp bị xóa khỏi hoặc được thêm vào thư mục dirpath trong khi tạo danh sách, liệu tên của tệp đó có được đưa vào hay không sẽ không được chỉ định
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]. No matter the value of topdown, the list of subdirectories is retrieved before the tuples for the directory and its subdirectories are generated
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 directories26 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
Nâng cao 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 directories35 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 directories36,
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 directories37,
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 directories38,
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 directories39
Đã thay đổi trong phiên bản 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. fwalk[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 directories44 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 directories52 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 directories36,
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 directories37,
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 directories38,
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 directories56,
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]]Tạo một tệp ẩn danh và trả về một bộ mô tả tệp đề cập đến nó. flags must be 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 directories59 constants available on the system [or a bitwise ORed combination of them]. 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 directories60. 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 directories61 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_16GBNhững cờ này có thể được chuyển đến
Linux >= 3. 17 với 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 directories63 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à
If is specified and the event counter is non-zero, returns 1 and decrements the counter by one
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, sẽ 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_SEMAPHORECung 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. thuộc tính có thể là byte hoặc str [trực tiếp hoặc gián tiếp thông qua giao diện]. Nếu là str, nó được mã hóa bằng mã hóa hệ thống tệp
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 directories87 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 directories89
Đã thay đổi trong phiên bản 3. 6. Chấp nhận đường dẫn và thuộc tính for.
os. listxattr[path=None , * , 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 directories92 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 directories95 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 directories89
Đã 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 caused the flags argument to be ignored on some filesystems
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 directories89,
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_MAXKí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
Đâ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
Các chức năng khác nhau lấy danh sách các đối số cho chương trình mới được tải vào quy trình. 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. For example,
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"015 will only print
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"016 on standard output;
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"017 will seem to be ignoredos. 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ớios. 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, hai cách chính mà tệp DLL được tải hiện sẽ ghi đè rõ ràng hành vi trên toàn quy trình để đảm bảo tính nhất quán. 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]Tất cả các chức năng này thực hiện một chương trình mới, thay thế quy trình hiện tại; . 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ã; . The “v” variants are good when the number of parameters is variable, with the arguments being passed in a list or tuple as the args parameter. 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ể. These constants are defined where they are defined by the underlying platform
os. EX_OKMã 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_USAGEMã 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_DATAERRMã 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_NOINPUTMã 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_NOUSERMã 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_NOHOSTExit code that means a specified host did not exist
Unix, not Emscripten, not WASI
os. EX_UNAVAILABLEMã 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_SOFTWAREMã 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_OSERRMã 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_OSFILEMã 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_CANTCREATMã 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_IOERRMã 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_TEMPFAILMã thoát có nghĩa là đã xảy ra lỗi tạm thời. This indicates something that may not really be an error, such as a network connection that couldn’t be made during a retryable operation
Unix, not Emscripten, not WASI
os. EX_PROTOCOLMã 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_NOPERMMã 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_CONFIGMã thoát có nghĩa là đã xảy ra một số loại lỗi cấu hình
Unix, not Emscripten, not WASI
os. EX_NOTFOUNDMã 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 = 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 , chế độ='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 ;
not Emscripten, not 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ì
Đường dẫn đối số chỉ vị trí, args và env tương tự như
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"118os. POSIX_SPAWN_CLOSE
[
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"119, fd]
Performs
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"120os. 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ó. Nếu giá trị của setpgroup không được đặt, thì phần tử con sẽ kế thừa ID nhóm tiến trình 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"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 cấp phép 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
The sigdef argument will reset the disposition of all signals in the set specified. Đố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 là một hàm được gọi từ tiến trình cha sau khi rẽ nhánh một tiến trình con
after_in_child là một hàm được gọi từ tiến trình con
These calls are only made if control is expected to return to the Python interpreter. 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]Thực hiện đường dẫn chương trình trong một quy trình mới
[Lưu ý rằng mô-đun cung cấp các phương tiện mạnh mẽ hơn để sinh ra các quy trình mới và truy xuất kết quả của chúng; sử dụng mô-đun đó tốt hơn là sử dụng các chức năng này. Check especially the section. ]
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ể 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 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_NOWAITOCá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_WAITGiá 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_OVERLAYCá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ó
When operation is not specified or
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"214, this acts like double-clicking the file in Windows Explorer, or giving the file name as an argument to the start command from the interactive command shell. 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]
When launching an application, specify arguments to be passed as a single string. This argument may have no effect when using this function to launch a document
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
returns as soon as the associated application is launched. 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]
Execute the command [a string] in a subshell. Đ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. On Windows, the result is directly the exit code
Đư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. Giá trị trả về là một đối tượng có năm thuộc tính
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ùngif os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"
246 - giờ hệ thốngif os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"
247 - user time of all child processesif 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 conif 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
Xem thêm
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 Windowsos. waitid[idtype , id, options, /]
Đợi quá trình con hoàn thành
idtype có thể là , , hoặc [trên Linux]. Việc giải thích id phụ thuộc vào nó;
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 [process ID]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àoif 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. Chờ 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]
tùy chọn là tổ hợp cờ OR. 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. Other options that can be used are and
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à idif 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à idif 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. WEXITEDThis options flag for causes child processes that have terminated to be reported
Các hàm
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"323 khác luôn báo cáo các hàm con đã kết thúc, vì vậy tùy chọn này không khả dụng cho chúng
Unix, not Emscripten, not WASI
New in version 3. 3
os. DỪNG LẠITùy chọn này gắn cờ cho các nguyên nhân quy trình con đã bị dừng do gửi tín hiệu được báo cáo
Tùy chọn này không khả dụng cho các chức năng
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"323 khác
Unix, not Emscripten, not WASI
New in version 3. 3
os. BỎ QUATù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. WNOHANGCờ 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Ờ ĐỢICờ tùy chọn này khiến cho phần tử con ở trạng thái có thể chờ được, để 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
Tùy chọn này không khả dụng cho các chức năng
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"323 khác
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 0Nế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 0Nế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
Xem thêm
, , , , , 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. ĐÃ CÓ VỢ[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 đã 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_OTHERChính sách lập lịch trình mặc định
os. SCHED_BATCHChí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_IDLEChính sách lập lịch trình cho các tác vụ nền có mức độ ưu tiên cực thấp
os. SCHED_SPORADICChính sách lập lịch cho các chương trình máy chủ lẻ tẻ
os. SCHED_FIFOChính sách lập kế hoạch First In First Out
os. SCHED_RRChính sách lập lịch quay vòng
os. SCHED_RESET_ON_FORKCờ 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 biểu và mức độ ưu tiên của quy trình con được đặt lại về mặc định
lớp 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_priorityMứ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 tiến trình với PID pid. Một pid của 0 có nghĩa là quá trình gọi. 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. 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_namesCá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 , /]Trả về các giá trị cấu hình hệ thống có giá trị số nguyên. Nếu giá trị cấu hình được chỉ định theo tên không được xác định, thì ______3_______32 được trả về. Các nhận xét về tham số tên cũng được áp dụng ở đây;
Unix
os. sysconf_namesCá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
Đã thay đổi trong phiên bản 3. 11. Thêm tên
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"403.
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. Chúng được xác định cho tất cả các nền tảng
Các hoạt động cấp cao hơn trên tên đường dẫn được xác định trong mô-đun
os. sữa chuaChuỗi hằng số được hệ điều hành sử dụng để chỉ thư mục hiện tại. Đây là
os.stat in os.supports_dir_fd14 cho Windows và POSIX. Cũng có sẵn thông quaos. xin lỗi
Chuỗi hằng được hệ điều hành sử dụng để chỉ thư mục mẹ. Đây là
os.stat in os.supports_dir_fd15 cho Windows và POSIX. Cũng có sẵn thông quaos. tháng 9
Ký tự được hệ điều hành sử dụng để phân tách các thành phần tên đường dẫn. Đâ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. Lưu ý rằng biết điều này là không đủ để có thể phân tích cú pháp hoặc nối tên đường dẫn - sử dụng và - nhưng đôi khi nó hữu ích. Cũng có sẵn thông quaos. 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 tách. Điều này được đặt thành
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"221 trên các hệ thống Windows trong đó
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"416 là dấu gạch chéo ngược. Cũng có sẵn thông quaos. extsep
Ký tự phân tách tên tệp cơ sở với phần mở rộng; . Cũng có sẵn thông qua
os. pathsepKý tự thường được hệ điều hành sử dụng để phân tách các thành phần đường dẫn tìm kiếm [như trong
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"027], chẳng hạn như
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"422 cho POSIX hoặc
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"423 cho Windows. Cũng có sẵn thông quaos. 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. Cũng có sẵn thông quaos. dòng
Chuỗi được sử dụng để phân tách [hay đúng hơn là chấm dứt] các dòng trên nền tảng hiện tại. Đây có thể là một 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"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. Không sử dụng hệ điều hành. 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
Đường dẫn tệp của thiết bị null. 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. Cũng có sẵn thông quaos. 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[kích thước , cờ=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. Việc đọc một lượng lớn dữ liệu một cách không cần thiết sẽ có tác động tiêu cực đến những người dùng khác của thiết bị
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"438 và
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"439
Đố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 , /]Trả về một chuỗi byte ngẫu nhiên có kích thước phù hợp cho việc sử dụng mật mã
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
Trên Linux, nếu tòa nhà chọc trời
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"437 có sẵn, nó được sử dụng ở chế độ chặn. 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
Trên hệ thống giống Unix, các byte ngẫu nhiên được đọc từ thiết bị
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"439. Nếu thiết bị
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"439 không có sẵn hoặc không thể đọc được, ngoại lệ sẽ được đưa ra
Trên Windows, nó sẽ sử dụng
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"448
Xem thêm
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
Đã thay đổi trong phiên bản 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.
Đã thay đổi trong phiên bản 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. Trên 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. Trên 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ộ.
Đã thay đổi trong phiên bản 3. 11. Trên Windows,
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"448 được sử dụng thay vì
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"457 không được dùng nữa. os. GRND_NONBLOCK
Theo mặc định, khi đọc từ
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"438, nó sẽ chặn nếu không có byte ngẫu nhiên nào và khi đọc từ
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"439, nó sẽ chặn nếu nhóm entropy chưa được khởi tạo
Nếu cờ được đặt, thì không chặn trong những trường hợp này mà thay vào đó tăng ngay lập tức
New in version 3. 6
os. GRND_RANDOMNếu bit này được đặt, thì các byte ngẫu nhiên được lấy từ nhóm
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"438 thay vì nhóm
if os.access["myfile", os.R_OK]: with open["myfile"] as fp: return fp.read[] return "some default data"439