【发布时间】:2015-08-26 05:02:27
【问题描述】:
我有一个程序从 cli sys.argv[] 读取数据,然后将其写入文件。 我还想将输出显示到缓冲区。
手册说要使用 getvalue(),我得到的只是错误。 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()
错误:
# 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 流写入函数数据输出到缓冲区以及文件?
【问题讨论】:
-
你从哪里得到 fd?它不是 StringIO 对象。
-
@Aereaux 来自字符串 + sys.argv[]。这是完整的代码。 paste.ee/p/UkGpB
标签: python string io stream wrapper