##// END OF EJS Templates
cleanup entry point
Matthias BUSSONNIER -
Show More
@@ -20,101 +20,113 b' import sys'
20 import io
20 import io
21 import os
21 import os
22
22
23 from converters.template import *
24 from converters.template import ConverterTemplate
23 from converters.template import ConverterTemplate
25 from converters.html import ConverterHTML
26 # From IPython
24 # From IPython
27
25
28 # All the stuff needed for the configurable things
26 # All the stuff needed for the configurable things
29 from IPython.config.application import Application
27 from IPython.config.application import Application
30 from IPython.config.loader import ConfigFileNotFound
28 from IPython.config.loader import ConfigFileNotFound
31 from IPython.utils.traitlets import List, Unicode, Type, Bool, Dict, CaselessStrEnum
29 from IPython.utils.traitlets import Unicode, Bool
32
30
33 from converters.transformers import (ConfigurableTransformers,ExtractFigureTransformer)
31 from converters.transformers import (ExtractFigureTransformer)
34
32
35 from converters.jinja_filters import GlobalConfigurable
33 from converters.jinja_filters import GlobalConfigurable
36
34
37
35
38 class NbconvertApp(Application):
36 class NbconvertApp(Application):
37 """A basic application to convert ipynb files
39
38
40 stdout = Bool(True, config=True)
39 """
41 write = Bool(False, config=True)
40
41 stdout = Bool(True, config=True,
42 help="""
43 Wether to print the converted ipynb file to stdout
44 use full do diff files without actually writing a new file
45 """)
42
46
43 fileext = Unicode('txt', config=True)
47 write = Bool(False, config=True,
48 help="""Shoudl the converted notebook file be written to disk
49 along with potential extracted resources.
50 """
51 )
52
53 fileext = Unicode('txt', config=True,
54 help="""Extension of the file that should be written to disk"""
55 )
44
56
45 aliases = {
57 aliases = {
46 'stdout':'NbconvertApp.stdout',
58 'stdout':'NbconvertApp.stdout',
47 'write':'NbconvertApp.write',
59 'write':'NbconvertApp.write',
48 }
60 }
49
61
50 flags= {}
62 flags = {}
51 flags['no-stdout'] = (
63 flags['no-stdout'] = (
52 {'NbconvertApp' : {'stdout' : False}},
64 {'NbconvertApp' : {'stdout' : False}},
53 """the doc for this flag
65 """Do not print converted file to stdout, equivalent to --stdout=False
54
55 """
66 """
56 )
67 )
57
68
58 def __init__(self, **kwargs):
69 def __init__(self, **kwargs):
59 super(NbconvertApp, self).__init__(**kwargs)
70 super(NbconvertApp, self).__init__(**kwargs)
60 self.classes.insert(0,ConverterTemplate)
71 self.classes.insert(0, ConverterTemplate)
61 # register class here to have help with help all
72 # register class here to have help with help all
62 self.classes.insert(0,ExtractFigureTransformer)
73 self.classes.insert(0, ExtractFigureTransformer)
63 self.classes.insert(0,GlobalConfigurable)
74 self.classes.insert(0, GlobalConfigurable)
64 # ensure those are registerd
65
75
66 def load_config_file(self, profile_name):
76 def load_config_file(self, profile_name):
77 """load a config file from the config file dir
78
79 profile_name : {string} name of the profile file to load without file extension.
80 """
67 try:
81 try:
68 Application.load_config_file(
82 Application.load_config_file(
69 self,
83 self,
70 profile_name+'.nbcv',
84 profile_name+'.nbcv',
71 path=[os.path.join(os.getcwdu(),'profile')]
85 path=[os.path.join(os.getcwdu(), 'profile')]
72 )
86 )
87 return True
73 except ConfigFileNotFound:
88 except ConfigFileNotFound:
74 self.log.warn("Config file for profile '%s' not found, giving up ",profile_name)
89 self.log.warn("Config file for profile '%s' not found, giving up ", profile_name)
75 exit(1)
90 return False
76
91
77
92
78 def initialize(self, argv=None):
93 def initialize(self, argv=None):
94 """parse command line and load config"""
79 self.parse_command_line(argv)
95 self.parse_command_line(argv)
80 cl_config = self.config
96 cl_config = self.config
81 profile_file = sys.argv[1]
97 profile_file = argv[1]
82 self.load_config_file(profile_file)
98 if not self.load_config_file(profile_file):
99 exit(1)
83 self.update_config(cl_config)
100 self.update_config(cl_config)
84
101
85
102
86
103
87 def run(self):
104 def run(self):
88 """Convert a notebook to html in one step"""
105 """Convert a notebook in one step"""
89 template_file = (self.extra_args or [None])[0]
106 ipynb_file = (self.extra_args or [None])[2]
90 ipynb_file = (self.extra_args or [None])[1]
91
92 template_file = sys.argv[1]
93
107
94 C = ConverterTemplate(config=self.config)
108 C = ConverterTemplate(config=self.config)
95
109
96 output,resources = C.from_filename(ipynb_file)
110 output, resources = C.from_filename(ipynb_file)
97 if self.stdout :
111 if self.stdout :
98 print(output.encode('utf-8'))
112 print(output.encode('utf-8'))
99
113
100 out_root = ipynb_file[:-6].replace('.','_').replace(' ','_')
114 out_root = ipynb_file[:-6].replace('.', '_').replace(' ', '_')
101
115
102 keys = resources.get('figures',{}).keys()
116 keys = resources.get('figures', {}).keys()
103 if self.write :
117 if self.write :
104 with io.open(os.path.join(out_root+'.'+self.fileext),'w') as f:
118 with io.open(os.path.join(out_root+'.'+self.fileext), 'w') as f:
105 f.write(output)
119 f.write(output)
106 if keys :
120 if keys :
107 if self.write and not os.path.exists(out_root+'_files'):
121 if self.write:
108 os.mkdir(out_root+'_files')
122 files_dir = out_root+'_files'
109 for key in keys:
123 if not os.path.exists(out_root+'_files'):
110 if self.write:
124 os.mkdir(files_dir)
111 with io.open(os.path.join(out_root+'_files',key),'wb') as f:
125 for key in keys:
112 print(' writing to ',os.path.join(out_root,key))
126 with io.open(os.path.join(files_dir, key), 'wb') as f:
113 f.write(resources['figures'][key])
127 f.write(resources['figures'][key])
114 if self.stdout:
128 elif self.stdout:
115 print('''
129 print('''====================== Keys in Resources ==================================''')
116 ====================== Keys in Resources ==================================
117 ''')
118 print(resources['figures'].keys())
130 print(resources['figures'].keys())
119 print("""
131 print("""
120 ===========================================================================
132 ===========================================================================
@@ -127,7 +139,7 b' def main():'
127 """Convert a notebook to html in one step"""
139 """Convert a notebook to html in one step"""
128 app = NbconvertApp.instance()
140 app = NbconvertApp.instance()
129 app.description = __doc__
141 app.description = __doc__
130 app.initialize()
142 app.initialize(argv=sys.argv)
131 app.start()
143 app.start()
132 app.run()
144 app.run()
133 #-----------------------------------------------------------------------------
145 #-----------------------------------------------------------------------------
General Comments 0
You need to be logged in to leave comments. Login now