开发者

Can the formatter class be used without relying on an intermediate stream/file?

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 intermediat开发者_高级运维e 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.


You could use 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()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜