繁体   English   中英

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

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

我有一个程序,可以从cli sys.argv []中读取数据,然后将其写入文件。 我还想将输出显示到缓冲区。

手册说使用getvalue(),我得到的只是错误。 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()

错误:

 # 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

如何将io流写入功能数据中的数据输出到缓冲区以及文件中?

您使用open()打开文件,因此它不是StringIO对象,而是类似文件的对象。 要在写入文件后获取文件内容,可以使用mode = 'w+'打开文件,而不是fd.getvalue() ,请执行以下操作:

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

这会将文件的内容放入var。 但是,这也会使您进入文件的开头,因此请仔细进行进一步的写入。

暂无
暂无

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

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