##// END OF EJS Templates
Simplify ExecutePreprocessor using new context manager...
Thomas Kluyver -
Show More
@@ -46,38 +46,15 b' class ExecutePreprocessor(Preprocessor):'
46 }
46 }
47
47
48 extra_arguments = List(Unicode)
48 extra_arguments = List(Unicode)
49
50 def _create_client(self):
51 from IPython.kernel import KernelManager
52 self.km = KernelManager()
53 self.km.write_connection_file()
54 self.kc = self.km.client()
55 self.kc.start_channels()
56 self.km.start_kernel(extra_arguments=self.extra_arguments, stderr=open(os.devnull, 'w'))
57 self.iopub = self.kc.iopub_channel
58 self.shell = self.kc.shell_channel
59 self.shell.kernel_info()
60 try:
61 self.shell.get_msg(timeout=self.timeout)
62 except Empty:
63 self.log.error("Timeout waiting for kernel_info reply")
64 raise
65 # flush IOPub
66 while True:
67 try:
68 self.iopub.get_msg(block=True, timeout=0.25)
69 except Empty:
70 break
71
72 def _shutdown_client(self):
73 self.kc.stop_channels()
74 self.km.shutdown_kernel()
75 del self.km
76
49
77 def preprocess(self, nb, resources):
50 def preprocess(self, nb, resources):
78 self._create_client()
51 from IPython.kernel import run_kernel
79 nb, resources = super(ExecutePreprocessor, self).preprocess(nb, resources)
52 kernel_name = nb.metadata.get('kernelspec', {}).get('name', 'python')
80 self._shutdown_client()
53 with run_kernel(kernel_name=kernel_name,
54 extra_arguments=self.extra_arguments,
55 stderr=open(os.devnull, 'w')) as kc:
56 self.kc = kc
57 nb, resources = super(ExecutePreprocessor, self).preprocess(nb, resources)
81 return nb, resources
58 return nb, resources
82
59
83 def preprocess_cell(self, cell, resources, cell_index):
60 def preprocess_cell(self, cell, resources, cell_index):
@@ -87,7 +64,7 b' class ExecutePreprocessor(Preprocessor):'
87 if cell.cell_type != 'code':
64 if cell.cell_type != 'code':
88 return cell, resources
65 return cell, resources
89 try:
66 try:
90 outputs = self.run_cell(self.shell, self.iopub, cell)
67 outputs = self.run_cell(self.kc.shell_channel, self.kc.iopub_channel, cell)
91 except Exception as e:
68 except Exception as e:
92 self.log.error("failed to run cell: " + repr(e))
69 self.log.error("failed to run cell: " + repr(e))
93 self.log.error(str(cell.input))
70 self.log.error(str(cell.input))
General Comments 0
You need to be logged in to leave comments. Login now