comparison jupyter_c_kernel/kernel.py @ 54:7857f8eea835

Add args magic to provide cli-args to user program
author Ben Spoor <ben.spoor@altran.com>
date Thu, 13 Apr 2017 08:09:16 +0000
parents 0ef931211f77
children 40c903dde893
comparison
equal deleted inserted replaced
53:82b0505f1156 54:7857f8eea835
1 from queue import Queue 1 from queue import Queue
2 from threading import Thread 2 from threading import Thread
3 3
4 from ipykernel.kernelbase import Kernel 4 from ipykernel.kernelbase import Kernel
5 import re
5 import subprocess 6 import subprocess
6 import tempfile 7 import tempfile
7 import os 8 import os
8 import os.path as path 9 import os.path as path
9 10
116 args = ['gcc', source_filename] + cflags + ['-o', binary_filename] + ldflags 117 args = ['gcc', source_filename] + cflags + ['-o', binary_filename] + ldflags
117 return self.create_jupyter_subprocess(args) 118 return self.create_jupyter_subprocess(args)
118 119
119 def _filter_magics(self, code): 120 def _filter_magics(self, code):
120 121
121 magics = {'cflags': [], 'ldflags': []} 122 magics = {'cflags': [],
123 'ldflags': [],
124 'args': []}
122 125
123 for line in code.splitlines(): 126 for line in code.splitlines():
124 if line.startswith('//%'): 127 if line.startswith('//%'):
125 key, value = line[3:].split(":", 2) 128 key, value = line[3:].split(":", 2)
126 key = key.strip().lower() 129 key = key.strip().lower()
127 130
128 if key in ['ldflags', 'cflags']: 131 if key in ['ldflags', 'cflags']:
129 for flag in value.split(): 132 for flag in value.split():
130 magics[key] += [flag] 133 magics[key] += [flag]
134 elif key == "args":
135 # Split arguments respecting quotes
136 for argument in re.findall(r'(?:[^\s,"]|"(?:\\.|[^"])*")+', value):
137 magics['args'] += [argument.strip('"')]
131 138
132 return magics 139 return magics
133 140
134 def do_execute(self, code, silent, store_history=True, 141 def do_execute(self, code, silent, store_history=True,
135 user_expressions=None, allow_stdin=False): 142 user_expressions=None, allow_stdin=False):
149 "[C kernel] GCC exited with code {}, the executable will not be executed".format( 156 "[C kernel] GCC exited with code {}, the executable will not be executed".format(
150 p.returncode)) 157 p.returncode))
151 return {'status': 'ok', 'execution_count': self.execution_count, 'payload': [], 158 return {'status': 'ok', 'execution_count': self.execution_count, 'payload': [],
152 'user_expressions': {}} 159 'user_expressions': {}}
153 160
154 p = self.create_jupyter_subprocess([self.master_path, binary_file.name]) 161 p = self.create_jupyter_subprocess([self.master_path, binary_file.name] + magics['args'])
155 while p.poll() is None: 162 while p.poll() is None:
156 p.write_contents() 163 p.write_contents()
157 p.write_contents() 164 p.write_contents()
158 165
159 if p.returncode != 0: 166 if p.returncode != 0: