-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathipynb2py.py
76 lines (65 loc) · 2.28 KB
/
ipynb2py.py
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import getopt, sys
def usage():
print("""ipynb2py.py - Create an executable python script from a JupyterHub notebook .ipynb file
Usage: python ipynb2py.py --input|-i <inputFile> [--output|-o <outputFile>]
Outputs all the source code in the cells of the JupyterHub notebook.
<inputFile> specifies the JupyterHub notebook
<outputFile> specifies the filename to save the output to
If no <outputFile> is specified an outputFile name will be generated by replacing
the .ipynb extension with .py
python ipynb2py.py --help|-h
Display this help message and exit
""")
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "ho:i:", ["help", "output=", "input="])
except getopt.GetoptError as err:
# print help information and exit:
print(err) # will print something like "option -a not recognized"
usage()
sys.exit(2)
outputFile = None
inputFile = None
for o, a in opts:
if o in ("-h", "--help"):
usage()
sys.exit()
elif o in ("-i", "--input"):
inputFile = a
elif o in ("-o", "--output"):
outputFile = a
else:
assert False, "unhandled option"
if (inputFile == None):
print("no input file specified. Use -i or --input")
usage()
sys.exit()
if (outputFile == None):
dotPos = inputFile.rfind('.')
if (dotPos < 1):
outputFile = inputFile + ".py"
else:
outputFile = inputFile[0:dotPos] + ".py"
if (outputFile == inputFile):
print("input file is the same as output file")
usage()
sys.exit()
import json
file = open(inputFile)
jsonText = file.read()
file.close()
nb = json.loads(jsonText)
cells = nb["cells"]
file = open(outputFile, "w")
file.write("# Generated automatically from " + inputFile + "\n")
file.write("# Generated by ipynb2py.py\n")
file.write("#\n")
for elem in cells:
if "cell_type" in elem.keys() and elem["cell_type"] == "code" and "source" in elem.keys():
src = elem["source"]
for s in src:
file.write(s)
file.write("\n")
file.close()
if __name__ == "__main__":
main()