【问题标题】:how to write the output of iostream to buffer, python3如何将iostream的输出写入缓冲区,python3
【发布时间】: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


【解决方案1】:

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

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

这会将文件的内容放入var中。不过,这也会将您置于文件的开头,因此请小心进行进一步的写入。

【讨论】:

  • 我尝试了几种不同的方法,我从未收到任何输出paste.ee/p/9QFL7
  • 你需要通过fd.seek(0)回到起点。
  • '回溯?'我试着把它放在 fd 声明之后以及介于两者之间的任何地方。永远不要有任何输出到缓冲区。 :(
  • 在读取之前就这样做,否则会覆盖文件的一部分。
  • fd.seek(0)fd.read() 放在写入之后。另外,fd.read() 返回一个值,所以print 或者将其分配给一个变量。
猜你喜欢
  • 1970-01-01
  • 2012-10-22
  • 2015-06-11
  • 1970-01-01
  • 1970-01-01
  • 2012-04-15
  • 2023-03-23
  • 2015-07-31
  • 1970-01-01
相关资源
最近更新 更多