Python 是否可以在不依赖中间流/文件的情况下使用formatter类?

Python 是否可以在不依赖中间流/文件的情况下使用formatter类?,python,formatting,Python,Formatting,你可以用 谢谢这正是我想要的解决方案类型:) 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

你可以用


谢谢这正是我想要的解决方案类型:)
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.
>>> 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()