En Python, comme en Bash, il est possible de rediriger tous les flux des commandes d'affichages (print, pprint, etc...) vers un fichier.
Voici un exemple tout simple:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
from pprint import pprint
# We open the log file in writting mode
with open('myLogFile', 'w') as f:
# We redirect the 'sys.stdout' command towards the descriptor file
sys.stdout = f
# Now, all the print commands write directly in the file
print('This is a test.')
D = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
pprint(D)
A = 'Hello, how are you ?\n'
sys.stdout.write(A)
Quand on exécute le script:
# python3 testStdoutToFile.py
# cat myLogFile
This is a test.
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
Hello, how are you ?
Soo simple !