Why the returned os.popen object does not support the next () call

Python docs os.popen::

Open the pipe in or out of a team. The return value is an open file object connected to a channel that can be read or written depending on whether the mode is "r" (default) or "w".

I can use the next X.__next__()/ X.next()(2.X) method , but not a call next(x),

  • not a __next__method and next(x)the same thing?
  • Why can't we use next(x)for an object os.popen?

And last but not least, how do the methods work next()and next?

+4
source share
2 answers

(Python 3.4), __next__ _wrap_close, next() , __next__ . __next__ - __getattr__.

:

def popen(cmd, mode="r", buffering=-1):
    if not isinstance(cmd, str):
        raise TypeError("invalid cmd type (%s, expected string)" % type(cmd))
    if mode not in ("r", "w"):
        raise ValueError("invalid mode %r" % mode)
    if buffering == 0 or buffering is None:
        raise ValueError("popen() does not support unbuffered streams")
    import subprocess, io
    if mode == "r":
        proc = subprocess.Popen(cmd,
                                shell=True,
                                stdout=subprocess.PIPE,
                                bufsize=buffering)
        return _wrap_close(io.TextIOWrapper(proc.stdout), proc)
    else:
        proc = subprocess.Popen(cmd,
                                shell=True,
                                stdin=subprocess.PIPE,
                                bufsize=buffering)
        return _wrap_close(io.TextIOWrapper(proc.stdin), proc)

# Helper for popen() -- a proxy for a file whose close waits for the process
class _wrap_close:
    def __init__(self, stream, proc):
        self._stream = stream
        self._proc = proc
    def close(self):
        self._stream.close()
        returncode = self._proc.wait()
        if returncode == 0:
            return None
        if name == 'nt':
            return returncode
        else:
            return returncode << 8  # Shift left to match old behavior
    def __enter__(self):
        return self
    def __exit__(self, *args):
        self.close()
    def __getattr__(self, name):
        return getattr(self._stream, name)
    def __iter__(self):
        return iter(self._stream)
+5

https://docs.python.org/2/library/functions.html#next next:

, next(). , , , StopIteration .

:

TypeError: _wrap_close object is not an iterator

, . , __iter__.

, , Python 2.x:

>>> next(os.popen('ls'))
'foo.txt\n'
0

Source: https://habr.com/ru/post/1545639/


All Articles