簡體   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