I have a self-referential problem: I code programs for a book and like to keep nice and long jupyter notebooks for teaching and developing. From these I would like to automatically extract all files needed as listings for the book. I have created a version that works:
fname = "Export"
function export_code_segments(fname)
run(`jupyter nbconvert --to script $(fname).ipynb`);
open(fname*".jl") do file_in
file_content = read(file_in, String)
split_contents = split(file_content,"###EXPORT CODE")
for code_segment in split_contents
code_listing = split(code_segment,"FROM HERE ###")
if (code_listing[1][1:9] == " TO FILE ")
segment_name = strip(code_listing[1][9:end]);
segment_content = code_listing[2];
open(segment_name, "w") do file_out
write(file_out, strip(segment_content));
end
end
end
end
end
###EXPORT CODE TO FILE myfun.jl FROM HERE ###
for t=1:10
a = a + t;
end
println(a)
###EXPORT CODE UNTIL HERE ###
export_code_segments(fname)
open("myfun.jl") do file
for i in enumerate(eachline(file)) #for ln in eachline(ss)
println("$(i[1]): $(i[2])")
end
end
BUT is there a “proper way” to do this? I am sure more people thought about such problems, right?
Thanks!