Created
May 9, 2017 07:59
-
-
Save lucasjinreal/b182a9f79e602a8c8d02e62469c0c2fb to your computer and use it in GitHub Desktop.
Convert iPython Notebook to Pure Python Code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
# file: notebook_to_python.py | |
# author: JinTian | |
# time: 09/05/2017 3:28 PM | |
# Copyright 2017 JinTian. All Rights Reserved. | |
# | |
# Licensed under the Apache License, Version 2.0 (the "License"); | |
# you may not use this file except in compliance with the License. | |
# You may obtain a copy of the License at | |
# | |
# http://www.apache.org/licenses/LICENSE-2.0 | |
# | |
# Unless required by applicable law or agreed to in writing, software | |
# distributed under the License is distributed on an "AS IS" BASIS, | |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
# See the License for the specific language governing permissions and | |
# limitations under the License. | |
# ------------------------------------------------------------------------ | |
import sys | |
import os | |
import json | |
import ast | |
import numpy as np | |
def get_code(): | |
args = sys.argv | |
if len(args) < 2: | |
print('must specific notebook file path.') | |
exit() | |
else: | |
notebook_file = args[1] | |
file_name = os.path.basename(notebook_file).split('.')[0] | |
save_py_file = os.path.join(os.path.dirname(notebook_file), file_name + '.py') | |
print(notebook_file) | |
with open(notebook_file, 'r') as f: | |
notebook_dict = json.load(f) | |
cells = notebook_dict['cells'] | |
print(len(cells)) | |
all_codes = [c['source'] for c in cells if c['cell_type'] == 'code'] | |
all_sent = [] | |
for i in all_codes: | |
for s in i: | |
if not s.endswith('\n'): | |
s += '\n' | |
all_sent.append(s) | |
with open(save_py_file, 'w') as f: | |
f.writelines(all_sent) | |
print('convert success.') | |
if __name__ == '__main__': | |
get_code() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment