import formatter
# a long string I want to format
s="""When running behind a load balancer like nginx, it is recommended to pass xheaders=True to the HTTPServer constructor. This will tell Tornado to use
headers like X-Real-IP to get the user's IP address instead of attributing all traffic to the balancer's IP address.
"""
fh=open("tmp.txt","w")
f=formatter.DumbWriter(fh)
f.send_flowing_data(s)
fh.close()
# how can i set 'results' to the formatted text without using an intermediate file?
# there doesn't seem to be a formatter method which returns a string in
# leiu of sending the data to the stream
results=open("tmp.txt").read()
print results
>>> When running behind a load balancer like nginx, it is recommended to
>>> pass xheaders=True to the HTTPServer constructor. This will tell Tornado
>>> to use headers like X-Real-IP to get the user's IP address instead of
>>> attributing all traffic to the balancer's IP address.
答案 0 :(得分:2)
您可以使用StringIO。
>>> import StringIO
>>> fh = StringIO.StringIO()
>>> f.send_flowing_data(s)
>>> print(fh.getvalue())
When running behind a load balancer like nginx, it is recommended to
pass xheaders=True to the HTTPServer constructor. This will tell Tornado
to use headers like X-Real-IP to get the user's IP address instead of
attributing all traffic to the balancer's IP address.
>>> fh.close()