简体   繁体   中英

Is iter(subprocess.Popen_instance.stdout.readline, '') a busy loop?

Lets consider following code construct:

p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in iter(p.stdout.readline, ''):
    print(line)

Is this for loop a busy loop, or will it wait for output data from process lazily? How can I check this? Regardless of answer, is it part of language specification or implementation detail of CPython?

I'm interested in both Python 2.x and Python 3.x, on major OSes (Windows, macOS, Linux) and their respective kernels.

Since readline blocks, the loop is only as busy as there is output available to read.

Test from command line:

#!/usr/bin/env python

import subprocess
args = ('cat', '-')
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in iter(p.stdout.readline, ''):
    print(line.rstrip('\n'))


$ ./x.py
a
a
b
b
<Ctrl-D>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM