[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1
But on some systems, os.open flags let us specify more advanced things like exclusive
access (O_EXCL) and nonblocking modes (O_NONBLOCK) when a file is opened. Some of
these flags are not portable across platforms (another reason to use built-in file objects
most of the time); see the library manual or run a dir(os) call on your machine for an
exhaustive list of other open flags available.
One final note here: using os.open w i t h t h e O_EXCL f l a g i s t h e m o s t p o r t a b l e w a y t o lock
files for concurrent updates or other process synchronization in Python today. We’ll
see contexts where this can matter in the next chapter, when we begin to explore
multiprocessing tools. Programs running in parallel on a server machine, for instance,
may need to lock files before performing updates, if multiple threads or processes might
attempt such updates at the same time.

Wrapping descriptors in file objects
We saw earlier how to go from file object to field descriptor with the fileno file object
method; given a descriptor, we can use os module tools for lower-level file access to
the underlying file. We can also go the other way—the os.fdopen call wraps a file de-
scriptor in a file object. Because conversions work both ways, we can generally use
either tool set—file object or os module:
>>> fdfile = os.open(r'C:\temp\spam.txt', (os.O_RDWR | os.O_BINARY))
>>> fdfile
3
>>> objfile = os.fdopen(fdfile, 'rb')
>>> objfile.read()
b'Jello stdio file\r\nHello descriptor file\n'
In fact, we can wrap a file descriptor in either a binary or text-mode file object: in text
mode, reads and writes perform the Unicode encodings and line-end translations we
studied earlier and deal in str strings instead of bytes:
C:\...\PP4E\System> python
>>> import os
>>> fdfile = os.open(r'C:\temp\spam.txt', (os.O_RDWR | os.O_BINARY))
>>> objfile = os.fdopen(fdfile, 'r')
>>> objfile.read()
'Jello stdio file\nHello descriptor file\n'
In Python 3.X, the built-in open call also accepts a file descriptor instead of a file name
string; in this mode it works much like os.fdopen, but gives you greater control—for
example, you can use additional arguments to specify a nondefault Unicode encoding
for text and suppress the default descriptor close. Really, though, os.fdopen accepts
the same extra-control arguments in 3.X, because it has been redefined to do little but
call back to the built-in open (see os.py in the standard library):
C:\...\PP4E\System> python
>>> import os
>>> fdfile = os.open(r'C:\temp\spam.txt', (os.O_RDWR | os.O_BINARY))
>>> fdfile
3

158 | Chapter 4: File and Directory Tools

Do


wnload from Wow! eBook <www.wowebook.com>

Free download pdf