Skip to content

Instantly share code, notes, and snippets.

@jcfr
Last active February 14, 2017 10:24
Show Gist options
  • Save jcfr/7366dda36f86deaea2d81ffee160bf3f to your computer and use it in GitHub Desktop.
Save jcfr/7366dda36f86deaea2d81ffee160bf3f to your computer and use it in GitHub Desktop.
Convenient (and very dumb) script used to update IPython notebooks by changing "print" statement into function call.
#!/usr/bin/env python
#
# Convenient (and very dumb) script used to update IPython notebooks by changing "print" statement into function call.
#
# Assumption(s):
#
# * There is one print statement per line
#
import os
import sys
py3 = sys.version_info[0] == 3
def fix_notebook_print(input_nb):
sys.stdout.write("Fixing %s" % path)
sys.stdout.flush()
updated_lines = []
matched = 0
with open(input_nb, "r") as content:
for line in content:
line = line.rstrip()
if "print " in line:
line = line.replace("print ", "print(").replace("\\n\",", ")\\n\",")
if line.endswith("\""):
line = line[:-1] + ")\""
matched += 1
updated_lines.append(line)
with open(input_nb, "w") as content:
for line in updated_lines:
content.write(line + "\n")
print(" - done (%d lines updated)" % matched)
if __name__ == "__main__":
if len(sys.argv) == 1:
print("usage: %s /path/to/file [/path/to/file [...]]" % os.path.basename(__file__))
exit(1)
for path in sys.argv[1:]:
fix_notebook_print(path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment