-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_reset_notebook_execution_counts.py
More file actions
62 lines (46 loc) · 1.6 KB
/
_reset_notebook_execution_counts.py
File metadata and controls
62 lines (46 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/env python3
"""Pre-commit hook to reset execution counts in Jupyter notebooks."""
import json
import sys
from pathlib import Path
def reset_notebook_execution_counts(notebook_path):
"""Reset all execution counts in a Jupyter notebook to None.
Parameters
----------
notebook_path : Path
Path to the Jupyter notebook file
Returns
-------
bool
True if changes were made, False otherwise
"""
with open(notebook_path, 'r', encoding='utf-8') as f:
notebook = json.load(f)
modified = False
# Reset execution_count for cells
for cell in notebook.get('cells', []):
if cell.get('cell_type') == 'code':
if cell.get('execution_count') is not None:
cell['execution_count'] = None
modified = True
# Always reset metadata (execution time, etc.)
if cell.get('metadata') is not None:
cell['metadata'] = dict()
modified = True
if modified:
with open(notebook_path, 'w', encoding='utf-8') as f:
json.dump(notebook, f, indent=1, ensure_ascii=False)
f.write('\n')
return modified
def main():
"""Process all notebook files passed as arguments."""
modified_files = []
for file_path in sys.argv[1:]:
path = Path(file_path)
if path.suffix == '.ipynb':
if reset_notebook_execution_counts(path):
modified_files.append(file_path)
print(f"Reset execution counts and metadata in {file_path}")
return 0
if __name__ == '__main__':
sys.exit(main())