我正在尝试创建一个日志文件,该文件使用 pprint globals() 接收变量信息并写入文件。但是由于我必须使用许多循环,有没有办法将每个循环期间的所有 pprint globals() 输出放在日志文件的末尾,如下所示:
import numpy as np
from pprint import pprint
A = np.array([1, 2, 3, 4])
f = open("log.txt", 'w')
n = 3
for i in range(n):
f.write(u'\u27A4 - %s\n'.encode('utf-8') % str(i))
A = A + 1
f.writelines(list(u' \u27B3 - %s\n'.encode('utf-8') % i for i in A))
pprint(globals(), f)
f.close()
输出
➤ - 0
➳ - 2
➳ - 3
➳ - 4
➳ - 5
{'A': array([2, 3, 4, 5]),
'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': '~/Stack exchange/pprint_global.py',
'__name__': '__main__',
'__package__': None,
'f': <open file 'log.txt', mode 'w' at 0xb66588b8>,
'i': 0,
'n': 2,
'np': <module 'numpy' from '/usr/lib/python2.7/dist-packages/numpy/__init__.pyc'>,
'pprint': <function pprint at 0xb6e2748c>}
➤ - 1
➳ - 3
➳ - 4
➳ - 5
➳ - 6
{'A': array([3, 4, 5, 6]),
'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': '~/Stack exchange/pprint_global.py',
'__name__': '__main__',
'__package__': None,
'f': <open file 'log.txt', mode 'w' at 0xb66588b8>,
'i': 1,
'n': 2,
'np': <module 'numpy' from '/usr/lib/python2.7/dist-packages/numpy/__init__.pyc'>,
'pprint': <function pprint at 0xb6e2748c>}
期望的输出
➤ - 0
➳ - 2
➳ - 3
➳ - 4
➳ - 5
➤ - 1
➳ - 3
➳ - 4
➳ - 5
➳ - 6
{'A': array([2, 3, 4, 5]),
'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': '~/Stack exchange/pprint_global.py',
'__name__': '__main__',
'__package__': None,
'f': <open file 'log.txt', mode 'w' at 0xb66588b8>,
'i': 0,
'n': 2,
'np': <module 'numpy' from '/usr/lib/python2.7/dist-packages/numpy/__init__.pyc'>,
'pprint': <function pprint at 0xb6e2748c>}
{'A': array([3, 4, 5, 6]),
'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__file__': '~/Stack exchange/pprint_global.py',
'__name__': '__main__',
'__package__': None,
'f': <open file 'log.txt', mode 'w' at 0xb66588b8>,
'i': 1,
'n': 2,
'np': <module 'numpy' from '/usr/lib/python2.7/dist-packages/numpy/__init__.pyc'>,
'pprint': <function pprint at 0xb6e2748c>}
第一印象是将 pprint 命令放在代码的末尾,但这不会在每个循环期间为我提供变量信息。它只会在循环结束时给我价值。简而言之,我需要将每个循环(有另一个写入日志命令)写入日志文件末尾的变量信息。