gpt4 book ai didi

python - 为什么 os.popen 的返回对象不支持 next() 调用

转载 作者:太空狗 更新时间:2023-10-30 02:45:29 25 4
gpt4 key购买 nike

Python 文档:os.popen:

Open a pipe to or from command. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'.

我可以使用 next 方法 X.__next__()/X.next() (2.X) 但是不是 next(x) 调用,

  • __next__ 方法和 next(x) 不是一样的吗?
  • 为什么我们不能将 next(x) 用于 os.popen 的对象?

最后但同样重要的是,next()next method 是如何工作的?

最佳答案

查看源代码(Python 3.4)似乎 __next__ 方法没有在 _wrap_close 类中实现,所以 next()调用失败,因为它无法在类中找到 __next__ 方法。由于覆盖了 __getattr__ 方法,显式 __next__ 调用有效。

相关source code :

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)

关于python - 为什么 os.popen 的返回对象不支持 next() 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24362007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com