简体   繁体   English

如何将iostream的输出写入缓冲区python3

[英]how to write the output of iostream to buffer, python3

I have a program that reads data from cli sys.argv[] and then writes it to a file. 我有一个程序,可以从cli sys.argv []中读取数据,然后将其写入文件。 I would like to also display the output to the buffer. 我还想将输出显示到缓冲区。

The manual says to use getvalue(), all I get are errors. 手册说使用getvalue(),我得到的只是错误。 Python3 manual Python3手册

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? 如何将io流写入功能数据中的数据输出到缓冲区以及文件中?

You use open() to open the file, so it isn't a StringIO object, but a file-like object. 您使用open()打开文件,因此它不是StringIO对象,而是类似文件的对象。 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: 要在写入文件后获取文件内容,可以使用mode = 'w+'打开文件,而不是fd.getvalue() ,请执行以下操作:

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

This will put the contents of the file into var. 这会将文件的内容放入var。 This will also put you at the beginning of the file, though, so be carefully doing further writes. 但是,这也会使您进入文件的开头,因此请仔细进行进一步的写入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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