2010-09-09 2 views
2
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. 

Répondre

2

Vous pouvez utiliser 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

Merci! c'est exactement le type de solution que je cherchais :) –

Questions connexes