J'ai un tas de print
appels que j'ai besoin d'écrire dans un fichier au lieu de stdout
. (Je n'ai pas du tout besoin de stdout
.)impression dans un fichier en Python: redirect vs argument du fichier d'impression vs écriture
Je considère trois approches. Y a-t-il des avantages (y compris la performance) pour chacun d'entre eux?
redirect pleine, que j'ai vu here:
import sys
saveout = sys.stdout
fsock = open('out.log', 'w')
sys.stdout = fsock
print(x)
# and many more print calls
# later if I ever need it:
# sys.stdout = saveout
# fsock.close()
Redirect dans chaque déclaration d'impression:
fsock = open('out.log', 'w')
print(x, file = fsock)
# and many more print calls
fonction Write:
fsock = open('out.log', 'w')
fsock.write(str(x))
# and many more write calls
si vous utilisez py3k read [diveintopython 3] (http://diveintopython3.org/) – SilentGhost
oublié d'ajouter que j'ai posé une question connexe il y a peu de temps. http://stackoverflow.com/questions/4090652/where-to-store-a-log-file-name-in-python – max
En cas de doute, profil. http://docs.python.org/py3k/library/profile.html –