Python 等同于条件中类似 C 的赋值

标签 python

<分区>

Possible Duplicate:
Assignment Condition in Python While Loop

这相当于什么:

while (line = p.stdout.readline()) != '':
    ...

在 Python 中?

我不喜欢这样做:

line = p.stdout.readline()
while line != '':
    sys.stdout.write(line)
    line = p.stdout.readline()

虽然我多年来一直在使用后者……但我怀疑没有其他选择。我以为 p.stdout 支持迭代,比如

for line in p.stdout:
    sys.stdout.write(line)

但不幸的是,它不像从 open() 返回的句柄那样。

编辑: 抱歉,我错了,它确实支持它,问题是我无法像使用 p.stdout.readline() 那样立即将其取出。添加 sys.stdout.flush() 似乎没有帮助,因此它必须在 p.stdout 中进行缓冲。

最佳答案

您可以使用内置函数 iter() 完成此操作使用双参数调用方法:

for line in iter(p.stdout.readline, ''):
    ...

相关文档:

iter(o[, sentinel])
...
If the second argument, sentinel, is given, then o must be a callable object. The iterator created in this case will call o with no arguments for each call to its next() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.

One useful application of the second form of iter() is to read lines of a file until a certain line is reached. The following example reads a file until the readline() method returns an empty string:

with open('mydata.txt') as fp:
    for line in iter(fp.readline, ''):
        process_line(line)

编辑:根据您的编辑,您的实际问题似乎与缓冲有关。根据上下文,我猜您正在使用 subprocess.Popen()stdout=subprocess.PIPE。而不是直接使用文件句柄 p.stdout 你应该是 p.communicate()读取子进程的输出。

关于Python 等同于条件中类似 C 的赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9217154/

相关文章:

python - 如果 colspecs 参数不包含第一列,则 Python 中 pandas 中的 read_fwf 不使用注释字符

python - 不使用 psycopg2 是否可以使用 Django PostgreSQL 后端? cPanel 和共享主机部署限制

python - Sympy 解决方案中的 NotImplementedError

python - 想广泛了解Python中索引的用法

python - 将 c++ vector 传递给 python 并返回

python - Numpy 和带有大数组的内存

python - 无法用python删除临时文件

python - 从 keras 模型中删除警告

python - 如何使用 AbstractBaseUser 或 AbstractUser 创建用户。 (登录错误)

Python 快速排序运行时错误 : Maximum Recursion Depth Exceeded in cmp