New in version 3.4. Source code: This module provides infrastructure for writing single-threaded concurrent code using coroutines, multiplexing I/O access over sockets and other resources, running network clients and servers, and other related primitives.
I'm trying to write a networked game with Pygame and asyncio, but I can't work out how to avoid hanging on reads. Here is my code for the client: @asyncio.coroutine def handleclient: print('Connected!' ) reader, writer = yield from asyncio.openconnection('localhost', 8000) while True: mouseup = False for event in pygame.event.get: if event.type pygame.QUIT: pygame.quit sys.exit elif event.type pygame.MOUSEBUTTONUP: mouseup = True if mouseup: print('Writing') writer.write(b'Mouse up') print('Waiting to read') line = yield from reader.read(2.12) print(line.decode) writer.close This hangs on the line line = yield from reader.read(2.12). I previously thought that the point of asyncio was that it was non-blocking, and so if there wasn't any data to read it would just continue executing. I see now that this isn't the case. How do I integrate the asyncio networking code with the Pygame drawing and event code?
The point of yield from is to switch the execution to the asyncio's event loop and to block the current coroutine until the result is available. To schedule a task without blocking the current coroutine, you could use asyncio.async. To print read-so-far data without blocking the pygame loop: @asyncio.coroutine def read(reader, callback): while True: data = yield from reader.read(2.12) if not data: # EOF break callback(data) @asyncio.coroutine def echoclient: reader. Chunks = asyncio.async(read(reader, chunks.append)) while True: pygame.event.pump # advance pygame event loop.
If chunks: # print read-so-far data print(b'.join(chunks).decode) del chunks: yield from asyncio.sleep(0.016) # advance asyncio loop There should be no blocking calls inside the while loop. Read and sleep coroutines run concurrently in the same thread (obviously you could run other coroutines concurrently too). You can 'transform' a blocking task into a non-blocking one. I suggest this:. I have a function that listens to a twitter feed, function 'mention', and I run it in an executor, so if it hangs, it doesn't block the other tasks. @asyncio.coroutine def boucledeux: #faire attendre la boucle si pas bcp de mots while True: print('debut du deux') value = t.next future2 = loop.runinexecutor(None, mention, 'LQNyL2xvt9OQMvje7jryaHkN8', 'IRJX6S17K44t8oiVGCjrj6XCVKqGSX9ClfpGpfC467rajqePGb', '-km3Ufby8r9BbYpyzcqwiHhss22h4YkmnPN4LnLM', '53R8GAAncFJ1aHA1yJe1OICfjqUbqwcMR38wSqvbzsQMB', 23, value) response2 = yield from future2 yield from asyncio.sleep(5) print('fin du deux') asyncio.Task(boucledeux).
Well since you are trying to read the value of 'line' right after you call read you need that value at any cost. If the coroutine wouldn't stop cause there are no data, you could get an AttributeError on the line.decode call if 'line' then is None. One thing you can do is to set a timeout on the blocking call and handle the timeout exception. Print('Waiting to read') try: # block at most for one second line = yield from asyncio.waitfor(reader.read(2.12), 1) except asyncio.TimeoutError: continue else: print(line.decode).
Note Since this module has been designed primarily for Python 3.x, you have to be aware that all uses of “bytes” in this document refer to the type (of which bytes is an alias), and all uses of “text” refer to the type. Furthermore, those two types are not interchangeable in the APIs. At the top of the I/O hierarchy is the abstract base class. It defines the basic interface to a stream. Note, however, that there is no separation between reading and writing to streams; implementations are allowed to raise an if they do not support a given operation. Extending is which deals simply with the reading and writing of raw bytes to a stream. Subclasses to provide an interface to files in the machine’s file system.
Deals with buffering on a raw byte stream. Its subclasses, and buffer streams that are readable, writable, and both readable and writable. Provides a buffered interface to random access streams.
Is a simple stream of in-memory bytes. Another subclass, deals with streams whose bytes represent text, and handles encoding and decoding from and to strings., which extends it, is a buffered text interface to a buffered raw stream. Finally, is an in-memory stream for unicode text. Argument names are not part of the specification, and only the arguments of are intended to be used as keyword arguments. Module Interface io. DEFAULTBUFFERSIZE An int containing the default buffer size used by the module’s buffered I/O classes.
Uses the file’s blksize (as obtained by ) if possible. Open ( file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True ) Open file and return a corresponding stream. If the file cannot be opened, an is raised. File is either a string giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False.) mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode.
Other common values are 'w' for writing (truncating the file if it already exists), and 'a' for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position). In text mode, if encoding is not specified the encoding used is platform dependent. (For reading and writing raw bytes use binary mode and leave encoding unspecified.) The available modes are: Character Meaning 'r' open for reading (default) 'w' open for writing, truncating the file first 'a' open for writing, appending to the end of the file if it exists 'b' binary mode 't' text mode (default) '+' open a disk file for updating (reading and writing) 'U' universal newlines mode (for backwards compatibility; should not be used in new code) The default mode is 'rt' (open for reading text). For binary random access, the mode 'w+b' opens and truncates the file to 0 bytes, while 'r+b' opens the file without truncation.
Python distinguishes between files opened in binary and text modes, even when the underlying operating system doesn’t. Files opened in binary mode (including 'b' in the mode argument) return contents as bytes objects without any decoding. In text mode (the default, or when 't' is included in the mode argument), the contents of the file are returned as strings, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given.
Buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer 1 to indicate the size of a fixed-size chunk buffer. When no buffering argument is given, the default buffering policy works as follows:. Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device’s “block size” and falling back on. On many systems, the buffer will typically be 4096 or 8192 bytes long. “Interactive” text files (files for which isatty returns True) use line buffering.
Other text files use the policy described above for binary files. Encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever returns), but any encoding supported by Python can be used. See the module for the list of supported encodings. Errors is an optional string that specifies how encoding and decoding errors are to be handled—this cannot be used in binary mode. Pass 'strict' to raise a exception if there is an encoding error (the default of None has the same effect), or pass 'ignore' to ignore errors.
(Note that ignoring encoding errors can lead to data loss.) 'replace' causes a replacement marker (such as '?' ) to be inserted where there is malformed data. When writing, 'xmlcharrefreplace' (replace with the appropriate XML character reference) or 'backslashreplace' (replace with backslashed escape sequences) can be used. Any other error handling name that has been registered with is also valid.
Newline controls how works (it only applies to text mode). It can be None, ', ' n', ' r', and ' r n'. It works as follows:. On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in ' n', ' r', or ' r n', and these are translated into ' n' before being returned to the caller. If it is ', universal newlines mode is enabled, but line endings are returned to the caller untranslated.
If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated. On output, if newline is None, any ' n' characters written are translated to the system default line separator,. If newline is ', no translation takes place. If newline is any of the other legal values, any ' n' characters written are translated to the given string.
If closefd is False and a file descriptor rather than a filename was given, the underlying file descriptor will be kept open when the file is closed. If a filename is given closefd has no effect and must be True (the default). The type of file object returned by the function depends on the mode. When is used to open a file in a text mode ( 'w', 'r', 'wt', 'rt', etc.), it returns a subclass of (specifically ). When used to open a file in a binary mode with buffering, the returned class is a subclass of. The exact class varies: in read binary mode, it returns a; in write binary and append binary modes, it returns a, and in read/write mode, it returns a. When buffering is disabled, the raw stream, a subclass of, is returned.
It is also possible to use an or bytes string as a file for both reading and writing. For strings can be used like a file opened in text mode, and for bytes a can be used like a file opened in a binary mode. Exception io. BlockingIOError Error raised when blocking would occur on a non-blocking stream.
In addition to those of, has one attribute: characterswritten An integer containing the number of characters written to the stream before it blocked. Exception io. UnsupportedOperation An exception inheriting and that is raised when an unsupported operation is called on a stream.
I/O Base Classes class io. IOBase The abstract base class for all I/O classes, acting on streams of bytes. There is no public constructor. This class provides empty abstract implementations for many methods that derived classes can override selectively; the default implementations represent a file that cannot be read, written or seeked.
Even though does not declare read, readinto, or write because their signatures will vary, implementations and clients should consider those methods part of the interface. Matlab code for image processing. Also, implementations may raise an when operations they do not support are called. The basic type used for binary data read from or written to a file is bytes (also known as ). Method arguments may also be or of arrays of bytes.
In some cases, such as, a writable object such as is required. Text I/O classes work with data. Changed in version 2.7: Implementations should support arguments. Note that calling any method (even inquiries) on a closed stream is undefined. Implementations may raise in this case. IOBase (and its subclasses) support the iterator protocol, meaning that an object can be iterated over yielding the lines in a stream.
Lines are defined slightly differently depending on whether the stream is a binary stream (yielding bytes), or a text stream (yielding strings). IOBase is also a context manager and therefore supports the statement. In this example, file is closed after the statement’s suite is finished—even if an exception occurs. Open ( 'spam.txt', 'w' ) as file: file.
Write ( u 'Spam and eggs!' ) provides these data attributes and methods: close ( ) Flush and close this stream. This method has no effect if the file is already closed. Once the file is closed, any operation on the file (e.g. Reading or writing) will raise a.
As a convenience, it is allowed to call this method more than once; only the first call, however, will have an effect. Closed True if the stream is closed. Fileno ( ) Return the underlying file descriptor (an integer) of the stream if it exists. An is raised if the IO object does not use a file descriptor.
Flush ( ) Flush the write buffers of the stream if applicable. This does nothing for read-only and non-blocking streams. Isatty ( ) Return True if the stream is interactive (i.e., connected to a terminal/tty device). Readable ( ) Return True if the stream can be read from. If False, read will raise.
Readline ( limit=-1 ) Read and return one line from the stream. If limit is specified, at most limit bytes will be read. The line terminator is always b' n' for binary files; for text files, the newline argument to can be used to select the line terminator(s) recognized. Readlines ( hint=-1 ) Read and return a list of lines from the stream. Hint can be specified to control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all lines so far exceeds hint.
Note that it’s already possible to iterate on file objects using for line in file. Without calling file.readlines. Seek ( offset , whence ) Change the stream position to the given byte offset. Offset is interpreted relative to the position indicated by whence. The default value for whence is SEEKSET.
Values for whence are:. SEEKSET or 0 – start of the stream (the default); offset should be zero or positive. SEEKCUR or 1 – current stream position; offset may be negative. SEEKEND or 2 – end of the stream; offset is usually negative Return the new absolute position. New in version 2.7: The SEEK.
constants seekable ( ) Return True if the stream supports random access. If False, and will raise. Tell ( ) Return the current stream position. Truncate ( size=None ) Resize the stream to the given size in bytes (or the current position if size is not specified). The current stream position isn’t changed. This resizing can extend or reduce the current file size. In case of extension, the contents of the new file area depend on the platform (on most systems, additional bytes are zero-filled, on Windows they’re undetermined).
The new file size is returned. Writable ( ) Return True if the stream supports writing. If False, write and will raise.
Writelines ( lines ) Write a list of lines to the stream. Line separators are not added, so it is usual for each of the lines provided to have a line separator at the end. del ( ) Prepare for object destruction.
Provides a default implementation of this method that calls the instance’s method. RawIOBase Base class for raw binary I/O. There is no public constructor.
Raw binary I/O typically provides low-level access to an underlying OS device or API, and does not try to encapsulate it in high-level primitives (this is left to Buffered I/O and Text I/O, described later in this page). In addition to the attributes and methods from, RawIOBase provides the following methods: read ( n=-1 ) Read up to n bytes from the object and return them.
As a convenience, if n is unspecified or -1, is called. Otherwise, only one system call is ever made. Fewer than n bytes may be returned if the operating system call returns fewer than n bytes. If 0 bytes are returned, and n was not 0, this indicates end of file. If the object is in non-blocking mode and no bytes are available, None is returned.
Readall ( ) Read and return all the bytes from the stream until EOF, using multiple calls to the stream if necessary. Readinto ( b ) Read up to len(b) bytes into b, and return the number of bytes read. The object b should be a pre-allocated, writable array of bytes, either. If the object is in non-blocking mode and no bytes are available, None is returned.
Write ( b ) Write b to the underlying raw stream, and return the number of bytes written. The object b should be an array of bytes, either bytes,. The return value can be less than len(b), depending on specifics of the underlying raw stream, and especially if it is in non-blocking mode. None is returned if the raw stream is set not to block and no single byte could be readily written to it.
The caller may release or mutate b after this method returns, so the implementation should only access b during the method call. BufferedIOBase Base class for binary streams that support some kind of buffering. There is no public constructor. The main difference with is that methods, and will try (respectively) to read as much input as requested or to consume all given output, at the expense of making perhaps more than one system call.
In addition, those methods can raise if the underlying raw stream is in non-blocking mode and cannot take or give enough data; unlike their counterparts, they will never return None. Besides, the method does not have a default implementation that defers to. A typical implementation should not inherit from a implementation, but wrap one, like and do. Provides or overrides these methods and attribute in addition to those from: raw The underlying raw stream (a instance) that deals with.
This is not part of the API and may not exist on some implementations. Detach ( ) Separate the underlying raw stream from the buffer and return it. After the raw stream has been detached, the buffer is in an unusable state.
Some buffers, like, do not have the concept of a single raw stream to return from this method. New in version 2.7.
Read ( n=-1 ) Read and return up to n bytes. If the argument is omitted, None, or negative, data is read and returned until EOF is reached. An empty bytes object is returned if the stream is already at EOF. If the argument is positive, and the underlying raw stream is not interactive, multiple raw reads may be issued to satisfy the byte count (unless EOF is reached first).
But for interactive raw streams, at most one raw read will be issued, and a short result does not imply that EOF is imminent. A is raised if the underlying raw stream is in non blocking-mode, and has no data available at the moment. Read1 ( n=-1 ) Read and return up to n bytes, with at most one call to the underlying raw stream’s method.
This can be useful if you are implementing your own buffering on top of a object. Readinto ( b ) Read up to len(b) bytes into b, and return the number of bytes read.
The object b should be a pre-allocated, writable array of bytes, either. Like, multiple reads may be issued to the underlying raw stream, unless the latter is ‘interactive’. A is raised if the underlying raw stream is in non blocking-mode, and has no data available at the moment. Write ( b ) Write b, and return the number of bytes written (always equal to len(b), since if the write fails an will be raised). The object b should be an array of bytes, either bytes,. Depending on the actual implementation, these bytes may be readily written to the underlying stream, or held in a buffer for performance and latency reasons. When in non-blocking mode, a is raised if the data needed to be written to the raw stream but it couldn’t accept all the data without blocking.
The caller may release or mutate b after this method returns, so the implementation should only access b during the method call. Raw File I/O class io. FileIO ( name, mode='r', closefd=True ) represents an OS-level file containing bytes data. It implements the interface (and therefore the interface, too).
The name can be one of two things:. a string representing the path to the file which will be opened;. an integer representing the number of an existing OS-level file descriptor to which the resulting object will give access. The mode can be 'r', 'w' or 'a' for reading (default), writing, or appending. The file will be created if it doesn’t exist when opened for writing or appending; it will be truncated when opened for writing. Add a '+' to the mode to allow simultaneous reading and writing. The read (when called with a positive argument), readinto and write methods on this class will only make one system call.
In addition to the attributes and methods from and, provides the following data attributes and methods: mode The mode as given in the constructor. Name The file name. This is the file descriptor of the file when no name is given in the constructor.
Buffered Streams Buffered I/O streams provide a higher-level interface to an I/O device than raw I/O does. BytesIO ( initialbytes ) A stream implementation using an in-memory bytes buffer. The optional argument initialbytes is a bytes object that contains initial data. Provides or overrides these methods in addition to those from and: getvalue ( ) Return bytes containing the entire contents of the buffer. Read1 ( ) In, this is the same as read. BufferedReader ( raw, buffersize=DEFAULTBUFFERSIZE ) A buffer providing higher-level access to a readable, sequential object.
When reading data from this object, a larger amount of data may be requested from the underlying raw stream, and kept in an internal buffer. The buffered data can then be returned directly on subsequent reads. The constructor creates a for the given readable raw stream and buffersize. If buffersize is omitted, is used.
Provides or overrides these methods in addition to those from and: peek ( n ) Return bytes from the stream without advancing the position. At most one single read on the raw stream is done to satisfy the call. The number of bytes returned may be less or more than requested. Read ( n ) Read and return n bytes, or if n is not given or negative, until EOF or if the read call would block in non-blocking mode.
Read1 ( n ) Read and return up to n bytes with only one call on the raw stream. If at least one byte is buffered, only buffered bytes are returned.
Otherwise, one raw stream read call is made. BufferedWriter ( raw, buffersize=DEFAULTBUFFERSIZE ) A buffer providing higher-level access to a writeable, sequential object. When writing to this object, data is normally held into an internal buffer. The buffer will be written out to the underlying object under various conditions, including:. when the buffer gets too small for all pending data;. when is called;.
when a seek is requested (for objects);. when the object is closed or destroyed. The constructor creates a for the given writeable raw stream. If the buffersize is not given, it defaults to. A third argument, maxbuffersize, is supported, but unused and deprecated. Provides or overrides these methods in addition to those from and: flush ( ) Force bytes held in the buffer into the raw stream. A should be raised if the raw stream blocks.
Write ( b ) Write b, and return the number of bytes written. The object b should be an array of bytes, either bytes,. When in non-blocking mode, a is raised if the buffer needs to be written out but the raw stream blocks. BufferedRandom ( raw, buffersize=DEFAULTBUFFERSIZE ) A buffered interface to random access streams. It inherits and, and further supports seek and tell functionality. The constructor creates a reader and writer for a seekable raw stream, given in the first argument. If the buffersize is omitted it defaults to.
The most common release is 8.0.2.021, with over 98% of all installations currently using this version. Free movieplus x6 (win xpvistawin 7) programs.
A third argument, maxbuffersize, is supported, but unused and deprecated. Is capable of anything or can do.
BufferedRWPair ( reader, writer, buffersize=DEFAULTBUFFERSIZE ) A buffered I/O object combining two unidirectional objects – one readable, the other writeable – into a single bidirectional endpoint. Reader and writer are objects that are readable and writeable respectively.
If the buffersize is omitted it defaults to. A fourth argument, maxbuffersize, is supported, but unused and deprecated. Implements all of ’s methods except for, which raises.
Text I/O class io. TextIOBase Base class for text streams. This class provides a unicode character and line based interface to stream I/O. There is no readinto method because Python’s strings are immutable. There is no public constructor.
Provides or overrides these data attributes and methods in addition to those from: encoding The name of the encoding used to decode the stream’s bytes into strings, and to encode strings into bytes. Errors The error setting of the decoder or encoder. Newlines A string, a tuple of strings, or None, indicating the newlines translated so far. Depending on the implementation and the initial constructor flags, this may not be available. Buffer The underlying binary buffer (a instance) that deals with. This is not part of the API and may not exist on some implementations. Detach ( ) Separate the underlying binary buffer from the and return it.
After the underlying buffer has been detached, the is in an unusable state. Some implementations, like, may not have the concept of an underlying buffer and calling this method will raise. New in version 2.7.
Read ( n ) Read and return at most n characters from the stream as a single. If n is negative or None, reads until EOF. Readline ( limit=-1 ) Read until newline or EOF and return a single unicode. If the stream is already at EOF, an empty string is returned. If limit is specified, at most limit characters will be read. Seek ( offset , whence ) Change the stream position to the given offset.
Behaviour depends on the whence parameter. The default value for whence is SEEKSET.
SEEKSET or 0: seek from the start of the stream (the default); offset must either be a number returned by, or zero. Any other offset value produces undefined behaviour. SEEKCUR or 1: “seek” to the current position; offset must be zero, which is a no-operation (all other values are unsupported). SEEKEND or 2: seek to the end of the stream; offset must be zero (all other values are unsupported). Return the new absolute position as an opaque number. New in version 2.7: The SEEK.
constants. Tell ( ) Return the current stream position as an opaque number.
The number does not usually represent a number of bytes in the underlying binary storage. Write ( s ) Write the string s to the stream and return the number of characters written. TextIOWrapper ( buffer, encoding=None, errors=None, newline=None, linebuffering=False ) A buffered text stream over a binary stream. Encoding gives the name of the encoding that the stream will be decoded or encoded with. It defaults to. Errors is an optional string that specifies how encoding and decoding errors are to be handled. Pass 'strict' to raise a exception if there is an encoding error (the default of None has the same effect), or pass 'ignore' to ignore errors.
(Note that ignoring encoding errors can lead to data loss.) 'replace' causes a replacement marker (such as '?' ) to be inserted where there is malformed data. When writing, 'xmlcharrefreplace' (replace with the appropriate XML character reference) or 'backslashreplace' (replace with backslashed escape sequences) can be used. Any other error handling name that has been registered with is also valid.
Newline controls how line endings are handled. It can be None, ', ' n', ' r', and ' r n'. It works as follows:. On input, if newline is None, mode is enabled. Lines in the input can end in ' n', ' r', or ' r n', and these are translated into ' n' before being returned to the caller. If it is ', universal newlines mode is enabled, but line endings are returned to the caller untranslated.
If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated. On output, if newline is None, any ' n' characters written are translated to the system default line separator,. If newline is ', no translation takes place. If newline is any of the other legal values, any ' n' characters written are translated to the given string. If linebuffering is True, flush is implied when a call to write contains a newline character. Provides one attribute in addition to those of and its parents: linebuffering Whether line buffering is enabled.
StringIO ( initialvalue=u', newline=u' n' ) An in-memory stream for unicode text. The initial value of the buffer can be set by providing initialvalue. If newline translation is enabled, newlines will be encoded as if. The stream is positioned at the start of the buffer.
The newline argument works like that of. The default is to consider only n characters as ends of lines and to do no newline translation.
If newline is set to None, newlines are written as n on all platforms, but universal newline decoding is still performed when reading. Provides this method in addition to those from and its parents: getvalue ( ) Return a unicode containing the entire contents of the buffer at any time before the object’s close method is called. Newlines are decoded as if by, although the stream position is not changed. Example usage.
Binary I/O By reading and writing only large chunks of data even when the user asks for a single byte, buffered I/O is designed to hide any inefficiency in calling and executing the operating system’s unbuffered I/O routines. The gain will vary very much depending on the OS and the kind of I/O which is performed (for example, on some contemporary OSes such as Linux, unbuffered disk I/O can be as fast as buffered I/O).
The bottom line, however, is that buffered I/O will offer you predictable performance regardless of the platform and the backing device. Therefore, it is most always preferable to use buffered I/O rather than unbuffered I/O. Text I/O Text I/O over a binary storage (such as a file) is significantly slower than binary I/O over the same storage, because it implies conversions from unicode to binary data using a character codec. This can become noticeable if you handle huge amounts of text data (for example very large log files). Also, TextIOWrapper.tell and TextIOWrapper.seek are both quite slow due to the reconstruction algorithm used., however, is a native in-memory unicode container and will exhibit similar speed to. Reentrancy Binary buffered objects (instances of, and ) are not reentrant. While reentrant calls will not happen in normal situations, they can arise if you are doing I/O in a handler.
If it is attempted to enter a buffered object again while already being accessed from the same thread, then a is raised. The above implicitly extends to text files, since the function will wrap a buffered object inside a. This includes standard streams and therefore affects the built-in function as well.
At least on POSIX (including Linux), the obvious answer is that nonblocking regular files don't exist. Regular files ALWAYS block, and ONONBLOCK is silently ignored. Similarly, poll/select et al. Will always tell you that a fd pointing to a regular file is ready for I/O, regardless of whether the data is ready in the page cache or still on disk (mostly relevant for reading).
EDIT And, since ONONBLOCK is a no-op for regular files, a read on a regular file will never set errno to EAGAIN, contrary to what another answer to this question claims. EDIT2 References: From the POSIX specification: 'File descriptors associated with regular files shall always select true for ready to read, ready to write, and error conditions.' From the POSIX specification: 'Regular files shall always poll TRUE for reading and writing.' The above suffices to imply that while perhaps not strictly prohibited, non-blocking regular files doesn't make sense as there would be no way to poll them except busy-waiting.
Beyond the above, there is at least some circumstantial evidence From the POSIX specification: The behavior for file descriptors referring to pipes, block special files, and character special files is defined. 'Otherwise, the behavior of ONONBLOCK is unspecified.' Some related links: And, even here on stackoverflow: As the answer by R. Points out, due to how page caching works, non-blocking for regular files is not very easily defined. What if by some mechanism you find out that data is ready for reading in the page cache, and then before you read it the kernel decides to kick that page out of cache due to memory pressure?
It's different for things like sockets and pipes, because correctness requires that data is not discarded just like that. Also, how would you select/poll for a seekable file descriptor?
We would like to show you a description here but the site won’t allow us. Official MARVELL Marvell Link Aggregation Protocol Drivers download center, download and update MARVELL Marvell Link Aggregation Protocol drivers in 3. Marvell link aggregation driver. (Link-Aggregation) problem. Marvell Yukon 88e8056 PCI-E and Marvell Yukon 88e8001/8003. Using Link Aggregation Protocol Driver v10.11.9.3 for Windows.
You'd need some new API that supported specifying which byte range in the file you're interested in. And the kernel implementation of that API would tie in to the VM system, as it would need to prevent the pages you're interested in from being kicked out. Which would imply that those pages would count against the process locked pages limit (see ulimit -l) in order to prevent a DOS. And, when would those pages be unlocked? This is a really good question. Non-blocking sockets return an empty string from recv rather than throwing a socket.error indicating that there's no data available.
For files though, there doesn't seem to be any direct indicator that's available to Python. The only mechanism I can think of for detecting EOF is to compare the current position of the file to the overall file size after receiving an empty string: def readnonblock( fd ): t = os.read(fd, 4096) if t ': if os.fstat(fd).stsize os.lseek(fd, 0, os.SEEKCUR): raise Exception('EOF reached') return t This, of course, assumes that regular files in non-blocking mode will actually return immediately rather than wait for data to be read from the disk. I'm not sure if that's true on Windows or Linux. It'd be worth testing but I wouldn't be surprised if reading of regular files even in non-blocking mode only returns an empty string when the actual EOF is encountered.
A nice trick that works well in c (YMMV) is that if the amount of data returned is less that the size of the buffer (i.e. The buffer is not full) you can safely assume that the transaction has completed. There then is a 1/buffersize probability that the last part of the file completely fills the buffer so for a high buffer size you can be reasonable sure that the transaction will end with a non-filled buffer and so if you test the quantity of data returned against the buffer size and they are not equal you know that either an error occured or the transaction is complete. Not sure if this will translate to python but that is my method for spotting EOFs. For files, setting the file descriptor as non-blocking does nothing - all IO is done blocking anyway. If you really need non-blocking file IO, you need to look in to aioread and friends, which are the asynchronous IO facility for file access. These are pretty non-portable and work somewhat flakily at times - so most projects have actually decided to use a separate process (or thread) for IO and just use blocking IO there.
Then again, maybe you are interested in somehow 'select':ing a file such that you would get notified when the file grows. As you've probably realized select, poll, etc.
Most software does this simply by polling the file every second or so - for example 'tail -f' does it's magic by polling. However, you can also get the kernel to notify you when the file is written to - and this happens by inotify and friends. There are some handy libraries wrapping all this up for you so you don't have to muck around with the specifics yourself. Namely, for python, inotifyx and pyinotify.
README.md python-nonblock Non-blocking python IO functions These are pure-python functions which perform non-blocking I/O in python. Nonblockread nonblockread provides the ability to read anything available on a buffer, like a file or a pipe or a socket, in a non-blocking fashion. Methods like readline will block until a newline is printed, etc. You can provide a limit (or default None is anything available) and up to that many bytes, if available, will be returned.
When the stream is closed on the other side, and you have already read all the data (i.e. You've already been returned all data and it's impossible that more will ever be there in the future), 'None' is returned. Def nonblockread(stream, limit=None, forceMode=None): ' nonblockread - Read any data available on the given stream (file, socket, etc) without blocking and regardless of newlines. @param stream - A stream (like a file object or a socket) @param limit - Max number of bytes to read.
If None or 0, will read as much data is available. @param forceMode - Default None.
Will be autodetected if None. If you want to explicitly force a mode, provide 'b' for binary (bytes) or 't' for text (Str). This determines the return type. @return - Any data available on the stream, or 'None' if the stream was closed on the other side and all data has already been read. ' Keep in mind that you can only read data that has been flushed from the other side, otherwise it does not exist on the buffer.
Give More Feedback
If you need to do nonblocking reads on sys.stdin coming from a terminal, you will need to use 'tty.setraw(sys.stdin)' to put it in raw mode. See examples/simpleGame.py for an example. Example usage: from nonblock import nonblockread pipe = subprocess.Popen('someProgram', stdout=subprocess.PIPE).
Comments are closed.
|
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |