r01_mage
r01_mage

Reputation: 31

How to get the content of an object after iterate on it?

After a 'for' loop on a <_io.TextIOWrapper > object, I get an empty string when I try to read it again.

#! python3

import subprocess
import sys

cmd = ['sudo', 'apt', 'update']
p = subprocess.Popen(
    cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
for line in p.stdout:
    sys.stdout.write(line)

print(p.stdout.read())

I am forced to create an array before and append to it.

#! python3

import subprocess
import sys

cmd = ['sudo', 'apt', 'update']
p = subprocess.Popen(
    cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)

stdout = []  # I create an array

for line in p.stdout:
    sys.stdout.write(line)
    stdout.append(line)  # And append to it

print(stdout)

Why does it behave like this? Is there a better way? Something like p.stdout.reset_object()?

Upvotes: 0

Views: 67

Answers (1)

zvone
zvone

Reputation: 19382

You have an iterator. Once an iterator is consumed, you cannot go back. If you want to iterate through it again, the easiest way is to create a list from it, as you did.

One thing that would be a bit nicer is to create the list in one go:

 stdout = list(p.stdout)

Then you can iterate over stdout as many times as you want.

Upvotes: 1

Related Questions