how to write the output of iostream to buffer, python3

3.7k views Asked by At

I have a program that reads data from cli sys.argv[] and then writes it to a file. I would like to also display the output to the buffer.

The manual says to use getvalue(), all I get are errors. Python3 manual

import io
import sys

label = sys.argv[1]
domain = sys.argv[2]
ipv4 = sys.argv[3]
ipv6 = sys.argv[4]

fd = open( domain+".external", 'w+')
fd.write(label+"."+domain+".        IN AAAA "+ipv6+"\n")

output = io.StringIO()
output.write('First line.\n')
print('Second line.', file=output)

# Retrieve file contents -- this will be
# 'First line.\nSecond line.\n'
contents = output.getvalue()

# Close object and discard memory buffer --
# .getvalue() will now raise an exception.
output.close()

print(fd)
fd.getvalue()

error:

 # python3.4 makecustdomain.py bubba domain.com 1.2.3.4 '2001::1'

<_io.TextIOWrapper name='domain.com.external' mode='w' encoding='US-ASCII'>
Traceback (most recent call last):
  File "makecustdomain.py", line 84, in <module>
    fd.getvalue()
AttributeError: '_io.TextIOWrapper' object has no attribute 'getvalue

How do I output the data from io stream write function data to buffer as well as to file?

1

There are 1 answers

5
Aereaux On BEST ANSWER

You use open() to open the file, so it isn't a StringIO object, but a file-like object. To get the contents of the file after you write to it you can open the file with mode = 'w+', and instead of fd.getvalue(), do:

fd.seek(0)
var = fd.read()

This will put the contents of the file into var. This will also put you at the beginning of the file, though, so be carefully doing further writes.