| 188 | |
| 189 | |
| 190 | def start_kernel(): |
| 191 | kernel_connection_file = os.path.join(os.getcwd(), "kernel_connection_file.json") |
| 192 | |
| 193 | if os.path.isfile(kernel_connection_file): |
| 194 | os.remove(kernel_connection_file) |
| 195 | if os.path.isdir(kernel_connection_file): |
| 196 | os.rmdir(kernel_connection_file) |
| 197 | |
| 198 | launch_kernel_script_path = os.path.join( |
| 199 | pathlib.Path(__file__).parent.resolve(), "launch_kernel.py" |
| 200 | ) |
| 201 | |
| 202 | os.makedirs('workspace/', exist_ok=True) |
| 203 | |
| 204 | kernel_process = subprocess.Popen( |
| 205 | [ |
| 206 | sys.executable, |
| 207 | launch_kernel_script_path, |
| 208 | "--IPKernelApp.connection_file", |
| 209 | kernel_connection_file, |
| 210 | "--matplotlib=inline", |
| 211 | "--quiet", |
| 212 | ], |
| 213 | cwd='workspace/' |
| 214 | ) |
| 215 | # Write PID for caller to kill |
| 216 | str_kernel_pid = str(kernel_process.pid) |
| 217 | os.makedirs(config.KERNEL_PID_DIR, exist_ok=True) |
| 218 | with open(os.path.join(config.KERNEL_PID_DIR, str_kernel_pid + ".pid"), "w") as p: |
| 219 | p.write("kernel") |
| 220 | |
| 221 | # Wait for kernel connection file to be written |
| 222 | while True: |
| 223 | if not os.path.isfile(kernel_connection_file): |
| 224 | sleep(0.1) |
| 225 | else: |
| 226 | # Keep looping if JSON parsing fails, file may be partially written |
| 227 | try: |
| 228 | with open(kernel_connection_file, 'r') as fp: |
| 229 | json.load(fp) |
| 230 | break |
| 231 | except json.JSONDecodeError: |
| 232 | pass |
| 233 | |
| 234 | # Client |
| 235 | kc = BlockingKernelClient(connection_file=kernel_connection_file) |
| 236 | kc.load_connection_file() |
| 237 | kc.start_channels() |
| 238 | kc.wait_for_ready() |
| 239 | return kc |
| 240 | |
| 241 | |
| 242 | if __name__ == "__main__": |