code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
return self.evaluate(.format(repr(selector), repr(btn)))
def click(self, selector, btn=0)
Click the targeted element. :param selector: A CSS3 selector to targeted element. :param btn: The number of mouse button. 0 - left button, 1 - middle button, 2 - right button
41.761219
70.787521
0.589952
script = 'document.querySelector("%s").setAttribute("value", "%s")' script = script % (selector, value) self.evaluate(script)
def set_input_value(self, selector, value)
Set the value of the input matched by given selector.
3.669223
3.802172
0.965033
return self.evaluate(.format(repr(selector), repr(classname)))
def set_class_value(self, selector, classname)
Set the class of element matched by the given selector.
28.56333
31.856037
0.896638
from spyder.utils.qthelpers import qapplication app = qapplication() widget = NotebookClient(plugin=None, name='') widget.show() widget.set_url('http://google.com') sys.exit(app.exec_())
def main()
Simple test.
4.404175
4.29964
1.024313
# Remove unneeded blank lines at the beginning eol = sourcecode.get_eol_chars(error) if eol: error = error.replace(eol, '<br>') # Don't break lines in hyphens # From http://stackoverflow.com/q/7691569/438386 error = error.replace('-', '&#8209') message = _("An error occurred while starting the kernel") kernel_error_template = Template(KERNEL_ERROR) page = kernel_error_template.substitute(css_path=CSS_PATH, message=message, error=error) self.setHtml(page)
def show_kernel_error(self, error)
Show kernel initialization errors.
5.691528
5.596585
1.016964
loading_template = Template(LOADING) loading_img = get_image_path('loading_sprites.png') if os.name == 'nt': loading_img = loading_img.replace('\\', '/') message = _("Connecting to kernel...") page = loading_template.substitute(css_path=CSS_PATH, loading_img=loading_img, message=message) self.setHtml(page)
def show_loading_page(self)
Show a loading animation while the kernel is starting.
4.719199
4.282454
1.101985
# Path relative to the server directory self.path = os.path.relpath(self.filename, start=server_info['notebook_dir']) # Replace backslashes on Windows if os.name == 'nt': self.path = self.path.replace('\\', '/') # Server url to send requests to self.server_url = server_info['url'] # Server token self.token = server_info['token'] url = url_path_join(self.server_url, 'notebooks', url_escape(self.path)) # Set file url to load this notebook self.file_url = self.add_token(url)
def register(self, server_info)
Register attributes that can be computed with the server info.
3.955504
4.005567
0.987502
if is_text_string(url_or_text): url = QUrl(url_or_text) else: url = url_or_text self.notebookwidget.load(url)
def go_to(self, url_or_text)
Go to page utl.
3.476504
3.537024
0.98289
sname = osp.splitext(osp.basename(self.filename))[0] if len(sname) > 20: fm = QFontMetrics(QFont()) sname = fm.elidedText(sname, Qt.ElideRight, 110) return sname
def get_short_name(self)
Get a short name for the notebook.
3.260557
3.045859
1.070489
sessions_url = self.get_session_url() sessions_req = requests.get(sessions_url).content.decode() sessions = json.loads(sessions_req) if os.name == 'nt': path = self.path.replace('\\', '/') else: path = self.path for session in sessions: notebook_path = session.get('notebook', {}).get('path') if notebook_path is not None and notebook_path == path: kernel_id = session['kernel']['id'] return kernel_id
def get_kernel_id(self)
Get the kernel id of the client. Return a str with the kernel id or None.
2.744715
2.692907
1.019239
kernel_id = self.get_kernel_id() if kernel_id: delete_url = self.add_token(url_path_join(self.server_url, 'api/kernels/', kernel_id)) delete_req = requests.delete(delete_url) if delete_req.status_code != 204: QMessageBox.warning( self, _("Server error"), _("The Jupyter Notebook server " "failed to shutdown the kernel " "associated with this notebook. " "If you want to shut it down, " "you'll have to close Spyder."))
def shutdown_kernel(self)
Shutdown the kernel of the client.
3.950003
3.855878
1.024411
def closing_plugin(self, cancelable=False): for cl in self.clients: cl.close() self.set_option('recent_notebooks', self.recent_notebooks) return True
Perform actions before parent main window is closed.
null
null
null
def refresh_plugin(self): nb = None if self.tabwidget.count(): client = self.tabwidget.currentWidget() nb = client.notebookwidget nb.setFocus() else: nb = None self.update_notebook_actions()
Refresh tabwidget.
null
null
null
def get_plugin_actions(self): create_nb_action = create_action(self, _("New notebook"), icon=ima.icon('filenew'), triggered=self.create_new_client) self.save_as_action = create_action(self, _("Save as..."), icon=ima.icon('filesaveas'), triggered=self.save_as) open_action = create_action(self, _("Open..."), icon=ima.icon('fileopen'), triggered=self.open_notebook) self.open_console_action = create_action(self, _("Open console"), icon=ima.icon( 'ipython_console'), triggered=self.open_console) self.clear_recent_notebooks_action =\ create_action(self, _("Clear this list"), triggered=self.clear_recent_notebooks) # Plugin actions self.menu_actions = [create_nb_action, open_action, self.recent_notebook_menu, MENU_SEPARATOR, self.save_as_action, MENU_SEPARATOR, self.open_console_action] self.setup_menu_actions() return self.menu_actions
Return a list of actions related to plugin.
null
null
null
def register_plugin(self): self.focus_changed.connect(self.main.plugin_focus_changed) self.main.add_dockwidget(self) self.ipyconsole = self.main.ipyconsole self.create_new_client(give_focus=False) icon_path = os.path.join(PACKAGE_PATH, 'images', 'icon.svg') self.main.add_to_fileswitcher(self, self.tabwidget, self.clients, QIcon(icon_path)) self.recent_notebook_menu.aboutToShow.connect(self.setup_menu_actions)
Register plugin in Spyder's main window.
null
null
null
def check_compatibility(self): message = '' value = True if PYQT4 or PYSIDE: message = _("You are working with Qt4 and in order to use this " "plugin you need to have Qt5.<br><br>" "Please update your Qt and/or PyQt packages to " "meet this requirement.") value = False return value, message
Check compatibility for PyQt and sWebEngine.
null
null
null
def setup_menu_actions(self): self.recent_notebook_menu.clear() self.recent_notebooks_actions = [] if self.recent_notebooks: for notebook in self.recent_notebooks: name = notebook action = \ create_action(self, name, icon=ima.icon('filenew'), triggered=lambda v, path=notebook: self.create_new_client(filename=path)) self.recent_notebooks_actions.append(action) self.recent_notebooks_actions += \ [None, self.clear_recent_notebooks_action] else: self.recent_notebooks_actions = \ [self.clear_recent_notebooks_action] add_actions(self.recent_notebook_menu, self.recent_notebooks_actions) self.update_notebook_actions()
Setup and update the menu actions.
null
null
null
def update_notebook_actions(self): if self.recent_notebooks: self.clear_recent_notebooks_action.setEnabled(True) else: self.clear_recent_notebooks_action.setEnabled(False) client = self.get_current_client() if client: if client.get_filename() != WELCOME: self.save_as_action.setEnabled(True) self.open_console_action.setEnabled(True) self.options_menu.clear() add_actions(self.options_menu, self.menu_actions) return self.save_as_action.setEnabled(False) self.open_console_action.setEnabled(False) self.options_menu.clear() add_actions(self.options_menu, self.menu_actions)
Update actions of the recent notebooks menu.
null
null
null
def add_to_recent(self, notebook): if notebook not in self.recent_notebooks: self.recent_notebooks.insert(0, notebook) self.recent_notebooks = self.recent_notebooks[:20]
Add an entry to recent notebooks. We only maintain the list of the 20 most recent notebooks.
null
null
null
def get_focus_client(self): widget = QApplication.focusWidget() for client in self.get_clients(): if widget is client or widget is client.notebookwidget: return client
Return current notebook with focus, if any.
null
null
null
def get_current_client(self): try: client = self.tabwidget.currentWidget() except AttributeError: client = None if client is not None: return client
Return the currently selected notebook.
null
null
null
def get_current_client_name(self, short=False): client = self.get_current_client() if client: if short: return client.get_short_name() else: return client.get_filename()
Get the current client name.
null
null
null
def create_new_client(self, filename=None, give_focus=True): # Generate the notebook name (in case of a new one) if not filename: if not osp.isdir(NOTEBOOK_TMPDIR): os.makedirs(NOTEBOOK_TMPDIR) nb_name = 'untitled' + str(self.untitled_num) + '.ipynb' filename = osp.join(NOTEBOOK_TMPDIR, nb_name) nb_contents = nbformat.v4.new_notebook() nbformat.write(nb_contents, filename) self.untitled_num += 1 # Save spyder_pythonpath before creating a client # because it's needed by our kernel spec. if not self.testing: CONF.set('main', 'spyder_pythonpath', self.main.get_spyder_pythonpath()) # Open the notebook with nbopen and get the url we need to render try: server_info = nbopen(filename) except (subprocess.CalledProcessError, NBServerError): QMessageBox.critical( self, _("Server error"), _("The Jupyter Notebook server failed to start or it is " "taking too much time to do it. Please start it in a " "system terminal with the command 'jupyter notebook' to " "check for errors.")) # Create a welcome widget # See issue 93 self.untitled_num -= 1 self.create_welcome_client() return welcome_client = self.create_welcome_client() client = NotebookClient(self, filename) self.add_tab(client) if NOTEBOOK_TMPDIR not in filename: self.add_to_recent(filename) self.setup_menu_actions() client.register(server_info) client.load_notebook() if welcome_client and not self.testing: self.tabwidget.setCurrentIndex(0)
Create a new notebook or load a pre-existing one.
null
null
null
def close_client(self, index=None, client=None, save=False): if not self.tabwidget.count(): return if client is not None: index = self.tabwidget.indexOf(client) if index is None and client is None: index = self.tabwidget.currentIndex() if index is not None: client = self.tabwidget.widget(index) is_welcome = client.get_filename() == WELCOME if not save and not is_welcome: client.save() wait_save = QEventLoop() QTimer.singleShot(1000, wait_save.quit) wait_save.exec_() path = client.get_filename() fname = osp.basename(path) nb_contents = nbformat.read(path, as_version=4) if ('untitled' in fname and len(nb_contents['cells']) > 0 and len(nb_contents['cells'][0]['source']) > 0): buttons = QMessageBox.Yes | QMessageBox.No answer = QMessageBox.question(self, self.get_plugin_title(), _("<b>{0}</b> has been modified." "<br>Do you want to " "save changes?".format(fname)), buttons) if answer == QMessageBox.Yes: self.save_as(close=True) if not is_welcome: client.shutdown_kernel() client.close() # Delete notebook file if it is in temporary directory filename = client.get_filename() if filename.startswith(get_temp_dir()): try: os.remove(filename) except EnvironmentError: pass # Note: notebook index may have changed after closing related widgets self.tabwidget.removeTab(self.tabwidget.indexOf(client)) self.clients.remove(client) self.create_welcome_client()
Close client tab from index or widget (or close current tab).
null
null
null
def create_welcome_client(self): if self.tabwidget.count() == 0: welcome = open(WELCOME).read() client = NotebookClient(self, WELCOME, ini_message=welcome) self.add_tab(client) return client
Create a welcome client with some instructions.
null
null
null
def save_as(self, name=None, close=False): current_client = self.get_current_client() current_client.save() original_path = current_client.get_filename() if not name: original_name = osp.basename(original_path) else: original_name = name filename, _selfilter = getsavefilename(self, _("Save notebook"), original_name, FILES_FILTER) if filename: nb_contents = nbformat.read(original_path, as_version=4) nbformat.write(nb_contents, filename) if not close: self.close_client(save=True) self.create_new_client(filename=filename)
Save notebook as.
null
null
null
def open_notebook(self, filenames=None): if not filenames: filenames, _selfilter = getopenfilenames(self, _("Open notebook"), '', FILES_FILTER) if filenames: for filename in filenames: self.create_new_client(filename=filename)
Open a notebook from file.
null
null
null
def open_console(self, client=None): if not client: client = self.get_current_client() if self.ipyconsole is not None: kernel_id = client.get_kernel_id() if not kernel_id: QMessageBox.critical( self, _('Error opening console'), _('There is no kernel associated to this notebook.')) return self.ipyconsole._create_client_for_kernel(kernel_id, None, None, None) ipyclient = self.ipyconsole.get_current_client() ipyclient.allow_rename = False self.ipyconsole.rename_client_tab(ipyclient, client.get_short_name())
Open an IPython console for the given client or the current one.
null
null
null
def add_tab(self, widget): self.clients.append(widget) index = self.tabwidget.addTab(widget, widget.get_short_name()) self.tabwidget.setCurrentIndex(index) self.tabwidget.setTabToolTip(index, widget.get_filename()) if self.dockwidget and not self.ismaximized: self.dockwidget.setVisible(True) self.dockwidget.raise_() self.activateWindow() widget.notebookwidget.setFocus()
Add tab.
null
null
null
def move_tab(self, index_from, index_to): client = self.clients.pop(index_from) self.clients.insert(index_to, client)
Move tab.
null
null
null
def set_stack_index(self, index, instance): if instance == self: self.tabwidget.setCurrentIndex(index)
Set the index of the current notebook.
null
null
null
with open(os.path.join(HERE, module, '_version.py'), 'r') as f: data = f.read() lines = data.split('\n') for line in lines: if line.startswith('VERSION_INFO'): version_tuple = ast.literal_eval(line.split('=')[-1].strip()) version = '.'.join(map(str, version_tuple)) break return version
def get_version(module='spyder_notebook')
Get version.
1.939748
1.926121
1.007075
servers = [si for si in notebookapp.list_running_servers() if filename.startswith(si['notebook_dir'])] try: return max(servers, key=lambda si: len(si['notebook_dir'])) except ValueError: return None
def find_best_server(filename)
Find the best server to open a notebook with.
3.844475
3.032996
1.26755
filename = osp.abspath(filename) home_dir = get_home_dir() server_info = find_best_server(filename) if server_info is not None: print("Using existing server at", server_info['notebook_dir']) return server_info else: if filename.startswith(home_dir): nbdir = home_dir else: nbdir = osp.dirname(filename) print("Starting new server") command = [sys.executable, '-m', 'notebook', '--no-browser', '--notebook-dir={}'.format(nbdir), '--NotebookApp.password=', "--KernelSpecManager.kernel_spec_class='{}'".format( KERNELSPEC)] if os.name == 'nt': creation_flag = 0x08000000 # CREATE_NO_WINDOW else: creation_flag = 0 # Default value if DEV: env = os.environ.copy() env["PYTHONPATH"] = osp.dirname(get_module_path('spyder')) proc = subprocess.Popen(command, creationflags=creation_flag, env=env) else: proc = subprocess.Popen(command, creationflags=creation_flag) # Kill the server at exit. We need to use psutil for this because # Popen.terminate doesn't work when creationflags or shell=True # are used. def kill_server_and_childs(pid): ps_proc = psutil.Process(pid) for child in ps_proc.children(recursive=True): child.kill() ps_proc.kill() atexit.register(kill_server_and_childs, proc.pid) # Wait ~25 secs for the server to be up for _x in range(100): server_info = find_best_server(filename) if server_info is not None: break else: time.sleep(0.25) if server_info is None: raise NBServerError() return server_info
def nbopen(filename)
Open a notebook using the best available server. Returns information about the selected server.
3.008704
2.99898
1.003243
result = self.collection.aggregate(pipeline, **kwargs) if pymongo.version_tuple < (3, 0, 0): result = result['result'] return result
def aggregate(self, pipeline, **kwargs)
Perform an aggregation and make sure that result will be everytime CommandCursor. Will take care for pymongo version differencies :param pipeline: {list} of aggregation pipeline stages :return: {pymongo.command_cursor.CommandCursor}
3.611606
3.310143
1.091072
for endpoint, func in app.view_functions.items(): app.view_functions[endpoint] = wrapHttpEndpoint(func)
def wrapAppEndpoints(app)
wraps all endpoints defined in the given flask app to measure how long time each endpoints takes while being executed. This wrapping process is supposed not to change endpoint behaviour. :param app: Flask application instance :return:
3.520911
4.763986
0.739068
if _is_initialized(): def wrapper(f): return wrapHttpEndpoint(f) return wrapper raise Exception( "before measuring anything, you need to call init_app()")
def profile(*args, **kwargs)
http endpoint decorator
17.068823
12.699333
1.344072
urlPath = CONF.get("endpointRoot", "flask-profiler") fp = Blueprint( 'flask-profiler', __name__, url_prefix="/" + urlPath, static_folder="static/dist/", static_url_path='/static/dist') @fp.route("/".format(urlPath)) @auth.login_required def index(): return fp.send_static_file("index.html") @fp.route("/api/measurements/".format(urlPath)) @auth.login_required def filterMeasurements(): args = dict(request.args.items()) measurements = collection.filter(args) return jsonify({"measurements": list(measurements)}) @fp.route("/api/measurements/grouped".format(urlPath)) @auth.login_required def getMeasurementsSummary(): args = dict(request.args.items()) measurements = collection.getSummary(args) return jsonify({"measurements": list(measurements)}) @fp.route("/api/measurements/<measurementId>".format(urlPath)) @auth.login_required def getContext(measurementId): return jsonify(collection.get(measurementId)) @fp.route("/api/measurements/timeseries/".format(urlPath)) @auth.login_required def getRequestsTimeseries(): args = dict(request.args.items()) return jsonify({"series": collection.getTimeseries(args)}) @fp.route("/api/measurements/methodDistribution/".format(urlPath)) @auth.login_required def getMethodDistribution(): args = dict(request.args.items()) return jsonify({ "distribution": collection.getMethodDistribution(args)}) @fp.route("/db/dumpDatabase") @auth.login_required def dumpDatabase(): response = jsonify({ "summary": collection.getSummary()}) response.headers["Content-Disposition"] = "attachment; filename=dump.json" return response @fp.route("/db/deleteDatabase") @auth.login_required def deleteDatabase(): response = jsonify({ "status": collection.truncate()}) return response @fp.after_request def x_robots_tag_header(response): response.headers['X-Robots-Tag'] = 'noindex, nofollow' return response app.register_blueprint(fp)
def registerInternalRouters(app)
These are the endpoints which are used to display measurements in the flask-profiler dashboard. Note: these should be defined after wrapping user defined endpoints via wrapAppEndpoints() :param app: Flask application instance :return:
2.402155
2.372697
1.012415
if self.kernel.mva is None: print("Can't show log because no session exists") else: return self.kernel.Display(HTML(self.kernel.cachedlog))
def line_showLog(self)
SAS Kernel magic to show the SAS log for the previous submitted code. This magic is only available within the SAS Kernel
19.063139
15.935843
1.196243
if self.kernel.mva is None: self.kernel._allow_stdin = True self.kernel._start_sas() print("Session Started probably not the log you want") full_log = highlight(self.kernel.mva.saslog(), SASLogLexer(), HtmlFormatter(full=True, style=SASLogStyle, lineseparator="<br>")) return self.kernel.Display(HTML(full_log))
def line_showFullLog(self)
SAS Kernel magic to show the entire SAS log since the kernel was started (last restarted) This magic is only available within the SAS Kernel
13.009521
9.877088
1.317141
prmpt = OrderedDict() for arg in args: assert isinstance(arg, str) prmpt[arg] = False if not len(self.code): if self.kernel.mva is None: self.kernel._allow_stdin = True self.kernel._start_sas() self.kernel.mva.submit(code=self.code, results="html", prompt=prmpt) else: self.kernel.promptDict = prmpt
def line_prompt4var(self, *args)
%%prompt4var - Prompt for macro variables that will be assigned to the SAS session. The variables will be prompted each time the line magic is executed. Example: %prompt4var libpath file1 filename myfile "~&file1."; libname data "&libpath";
8.427822
8.436977
0.998915
lines = re.split(r'[\n]\s*', log) i = 0 elog = [] for line in lines: i += 1 e = [] if line.startswith('ERROR'): logger.debug("In ERROR Condition") e = lines[(max(i - 15, 0)):(min(i + 16, len(lines)))] elog = elog + e tlog = '\n'.join(elog) logger.debug("elog count: " + str(len(elog))) logger.debug("tlog: " + str(tlog)) color_log = highlight(log, SASLogLexer(), HtmlFormatter(full=True, style=SASLogStyle, lineseparator="<br>")) # store the log for display in the showSASLog nbextension self.cachedlog = color_log # Are there errors in the log? if show the lines on each side of the error if len(elog) == 0 and len(output) > self.lst_len: # no error and LST output debug1 = 1 logger.debug("DEBUG1: " + str(debug1) + " no error and LST output ") return HTML(output) elif len(elog) == 0 and len(output) <= self.lst_len: # no error and no LST debug1 = 2 logger.debug("DEBUG1: " + str(debug1) + " no error and no LST") return HTML(color_log) elif len(elog) > 0 and len(output) <= self.lst_len: # error and no LST debug1 = 3 logger.debug("DEBUG1: " + str(debug1) + " error and no LST") return HTML(color_log) else: # errors and LST debug1 = 4 logger.debug("DEBUG1: " + str(debug1) + " errors and LST") return HTML(color_log + output)
def _which_display(self, log: str, output: str) -> HTML
Determines if the log or lst should be returned as the results for the cell based on parsing the log looking for errors and the presence of lst output. :param log: str log from code submission :param output: None or str lst output if there was any :return: The correct results based on log and lst :rtype: str
3.291021
3.181231
1.034512
if not code.strip(): return {'status': 'ok', 'execution_count': self.execution_count, 'payload': [], 'user_expressions': {}} if self.mva is None: self._allow_stdin = True self._start_sas() if self.lst_len < 0: self._get_lst_len() if code.startswith('Obfuscated SAS Code'): logger.debug("decoding string") tmp1 = code.split() decode = base64.b64decode(tmp1[-1]) code = decode.decode('utf-8') if code.startswith('showSASLog_11092015') == False and code.startswith("CompleteshowSASLog_11092015") == False: logger.debug("code type: " + str(type(code))) logger.debug("code length: " + str(len(code))) logger.debug("code string: " + code) if code.startswith("/*SASKernelTest*/"): res = self.mva.submit(code, "text") else: res = self.mva.submit(code, prompt=self.promptDict) self.promptDict = {} if res['LOG'].find("SAS process has terminated unexpectedly") > -1: print(res['LOG'], '\n' "Restarting SAS session on your behalf") self.do_shutdown(True) return res['LOG'] output = res['LST'] log = res['LOG'] return self._which_display(log, output) elif code.startswith("CompleteshowSASLog_11092015") == True and code.startswith('showSASLog_11092015') == False: full_log = highlight(self.mva.saslog(), SASLogLexer(), HtmlFormatter(full=True, style=SASLogStyle, lineseparator="<br>", title="Full SAS Log")) return full_log.replace('\n', ' ') else: return self.cachedlog.replace('\n', ' ')
def do_execute_direct(self, code: str, silent: bool = False) -> [str, dict]
This is the main method that takes code from the Jupyter cell and submits it to the SAS server :param code: code from the cell :param silent: :return: str with either the log or list
4.972196
4.837529
1.027838
if info['line_num'] > 1: relstart = info['column'] - (info['help_pos'] - info['start']) else: relstart = info['start'] seg = info['line'][:relstart] if relstart > 0 and re.match('(?i)proc', seg.rsplit(None, 1)[-1]): potentials = re.findall('(?i)^' + info['obj'] + '.*', self.strproclist, re.MULTILINE) return potentials else: lastproc = info['code'].lower()[:info['help_pos']].rfind('proc') lastdata = info['code'].lower()[:info['help_pos']].rfind('data ') proc = False data = False if lastproc + lastdata == -2: pass else: if lastproc > lastdata: proc = True else: data = True if proc: # we are not in data section should see if proc option or statement lastsemi = info['code'].rfind(';') mykey = 's' if lastproc > lastsemi: mykey = 'p' procer = re.search('(?i)proc\s\w+', info['code'][lastproc:]) method = procer.group(0).split(' ')[-1].upper() + mykey mylist = self.compglo[method][0] potentials = re.findall('(?i)' + info['obj'] + '.+', '\n'.join(str(x) for x in mylist), re.MULTILINE) return potentials elif data: # we are in statements (probably if there is no data) # assuming we are in the middle of the code lastsemi = info['code'].rfind(';') mykey = 's' if lastproc > lastsemi: mykey = 'p' mylist = self.compglo['DATA' + mykey][0] potentials = re.findall('(?i)^' + info['obj'] + '.*', '\n'.join(str(x) for x in mylist), re.MULTILINE) return potentials else: potentials = [''] return potentials
def get_completions(self, info)
Get completions from kernel for procs and statements.
3.758843
3.639188
1.03288
print("in shutdown function") if self.hist_file: with open(self.hist_file, 'wb') as fid: data = '\n'.join(self.hist_cache[-self.max_hist_cache:]) fid.write(data.encode('utf-8')) if self.mva: self.mva._endsas() self.mva = None if restart: self.Print("Restarting kernel...") self.reload_magics() self.restart_kernel() self.Print("Done!") return {'status': 'ok', 'restart': restart}
def do_shutdown(self, restart)
Shut down the app gracefully, saving history.
4.912403
4.662902
1.053508
import os import types import code # arbitrary module which stays in the same dir as pdb stdlibdir, _ = os.path.split(code.__file__) pyfile = os.path.join(stdlibdir, name + '.py') result = types.ModuleType(name) exec(compile(open(pyfile).read(), pyfile, 'exec'), result.__dict__) return result
def import_from_stdlib(name)
Copied from pdbpp https://bitbucket.org/antocuni/pdb
4.394624
3.887266
1.130518
if self.shell: globals_ = dict(_initial_globals) else: globals_ = dict(self.current_frame.f_globals) globals_['_'] = self.db.last_obj if cut is not None: globals_.setdefault('cut', cut) # For meta debuging purpose globals_['___wdb'] = self.db # Hack for function scope eval globals_.update(self.current_locals) for var, val in self.db.extra_vars.items(): globals_[var] = val self.db.extra_items = {} return globals_
def get_globals(self)
Get enriched globals
7.296063
7.037838
1.036691
exc_info = sys.exc_info() type_, value = exc_info[:2] self.db.obj_cache[id(exc_info)] = exc_info return '<a href="%d" class="inspect">%s: %s</a>' % ( id(exc_info), escape(type_.__name__), escape(repr(value)) )
def handle_exc(self)
Return a formated exception traceback for wdb.js use
4.492545
4.027781
1.11539
if message is None: message = self.handle_exc() else: message = escape(message) self.db.send( 'Echo|%s' % dump({ 'for': escape(title or '%s failed' % cmd), 'val': message }) )
def fail(self, cmd, title=None, message=None)
Send back captured exceptions
10.523821
9.799845
1.073876
sys.path.insert(0, os.getcwd()) args, extrargs = parser.parse_known_args() sys.argv = ['wdb'] + args.args + extrargs if args.file: file = os.path.join(os.getcwd(), args.file) if args.source: print('The source argument cannot be used with file.') sys.exit(1) if not os.path.exists(file): print('Error:', file, 'does not exist') sys.exit(1) if args.trace: Wdb.get().run_file(file) else: def wdb_pm(xtype, value, traceback): sys.__excepthook__(xtype, value, traceback) wdb = Wdb.get() wdb.reset() wdb.interaction(None, traceback, post_mortem=True) sys.excepthook = wdb_pm with open(file) as f: code = compile(f.read(), file, 'exec') execute(code, globals(), globals()) else: source = None if args.source: source = os.path.join(os.getcwd(), args.source) if not os.path.exists(source): print('Error:', source, 'does not exist') sys.exit(1) Wdb.get().shell(source)
def main()
Wdb entry point
2.915615
2.767653
1.053461
shutdown_request = TCPServer.shutdown_request def shutdown_request_patched(*args, **kwargs): thread = current_thread() shutdown_request(*args, **kwargs) if thread in _exc_cache: post_mortem_interaction(*_exc_cache.pop(thread)) TCPServer.shutdown_request = shutdown_request_patched
def _patch_tcpserver()
Patch shutdown_request to open blocking interaction after the end of the request
4.418472
3.742804
1.180525
try: linenum = '%d' % linenum id = ' id="%s%s"' % (self._prefix[side], linenum) except TypeError: # handle blank lines where linenum is '>' or '' id = '' # replace those things that would get confused with HTML symbols text = ( text.replace("&", "&amp;").replace(">", "&gt;").replace("<", "&lt;") ) type_ = 'neutral' if '\0+' in text: type_ = 'add' if '\0-' in text: if type_ == 'add': type_ = 'chg' type_ = 'sub' if '\0^' in text: type_ = 'chg' # make space non-breakable so they don't get compressed or line wrapped text = text.replace(' ', '&nbsp;').rstrip() return ( '<td class="diff_lno"%s>%s</td>' '<td class="diff_line diff_line_%s">%s</td>' % (id, linenum, type_, text) )
def _format_line(self, side, flag, linenum, text)
Returns HTML markup of "from" / "to" text lines side -- 0 or 1 indicating "from" or "to" text flag -- indicates if difference on line linenum -- line number (used for line number column) text -- line text to be marked up
4.930156
4.871673
1.012005
if self.frame: self.frame = self.frame.f_back return self.frame is None
def up(self)
Go up in stack and return True if top frame
7.908032
3.846054
2.056142
frame = frame or sys._getframe().f_back for i in range(skip): if not frame.f_back: break frame = frame.f_back wdb = Wdb.get(server=server, port=port) wdb.set_trace(frame) return wdb
def set_trace(frame=None, skip=0, server=None, port=None)
Set trace on current line, or on given frame
2.907951
2.880085
1.009675
wdb = Wdb.get(server=server, port=port) if not wdb.stepping: wdb.start_trace(full, frame or sys._getframe().f_back, below, under) return wdb
def start_trace( full=False, frame=None, below=0, under=None, server=None, port=None )
Start tracing program at callee level breaking on exception/breakpoints
4.763362
4.455428
1.069114
log.info('Stopping trace') wdb = Wdb.get(True) # Do not create an istance if there's None if wdb and (not wdb.stepping or close_on_exit): log.info('Stopping trace') wdb.stop_trace(frame or sys._getframe().f_back) if close_on_exit: wdb.die() return wdb
def stop_trace(frame=None, close_on_exit=False)
Stop tracing
6.025693
6.008332
1.00289
for sck in list(Wdb._sockets): try: sck.close() except Exception: log.warn('Error in cleanup', exc_info=True)
def cleanup()
Close all sockets at exit
8.203664
6.31772
1.298516
Wdb.get(server=server, port=port).shell(source=source, vars=vars)
def shell(source=None, vars=None, server=None, port=None)
Start a shell sourcing source or using vars as locals
6.619021
6.32889
1.045842
pid = os.getpid() thread = threading.current_thread() wdb = Wdb._instances.get((pid, thread)) if not wdb and not no_create: wdb = object.__new__(Wdb) Wdb.__init__(wdb, server, port, force_uuid) wdb.pid = pid wdb.thread = thread Wdb._instances[(pid, thread)] = wdb elif wdb: if (server is not None and wdb.server != server or port is not None and wdb.port != port): log.warn('Different server/port set, ignoring') else: wdb.reconnect_if_needed() return wdb
def get(no_create=False, server=None, port=None, force_uuid=None)
Get the thread local singleton
2.958857
2.897688
1.02111
pid = os.getpid() thread = threading.current_thread() Wdb._instances.pop((pid, thread))
def pop()
Remove instance from instance list
10.126089
10.230076
0.989835
import __main__ __main__.__dict__.clear() __main__.__dict__.update({ "__name__": "__main__", "__file__": filename, "__builtins__": __builtins__, }) with open(filename, "rb") as fp: statement = compile(fp.read(), filename, 'exec') self.run(statement, filename)
def run_file(self, filename)
Run the file `filename` with trace
2.586219
2.636474
0.980939
if globals is None: import __main__ globals = __main__.__dict__ if locals is None: locals = globals self.reset() if isinstance(cmd, str): str_cmd = cmd cmd = compile(str_cmd, fn or "<wdb>", "exec") self.compile_cache[id(cmd)] = str_cmd if fn: from linecache import getline lno = 1 while True: line = getline(fn, lno, globals) if line is None: lno = None break if executable_line(line): break lno += 1 self.start_trace() if lno is not None: self.breakpoints.add(LineBreakpoint(fn, lno, temporary=True)) try: execute(cmd, globals, locals) finally: self.stop_trace()
def run(self, cmd, fn=None, globals=None, locals=None)
Run the cmd `cmd` with trace
3.487288
3.4475
1.011541
log.info('Connecting socket on %s:%d' % (self.server, self.port)) tries = 0 while not self._socket and tries < 10: try: time.sleep(.2 * tries) self._socket = Socket((self.server, self.port)) except socket.error: tries += 1 log.warning( 'You must start/install wdb.server ' '(Retrying on %s:%d) [Try #%d/10]' % (self.server, self.port, tries) ) self._socket = None if not self._socket: log.warning('Could not connect to server') return Wdb._sockets.append(self._socket) self._socket.send_bytes(self.uuid.encode('utf-8'))
def connect(self)
Connect to wdb server
4.196452
3.910954
1.073
fun = getattr(self, 'handle_' + event, None) if not fun: return self.trace_dispatch below, continue_below = self.check_below(frame) if (self.state.stops(frame, event) or (event == 'line' and self.breaks(frame)) or (event == 'exception' and (self.full or below))): fun(frame, arg) if event == 'return' and frame == self.state.frame: # Upping state if self.state.up(): # No more frames self.stop_trace() return # Threading / Multiprocessing support co = self.state.frame.f_code if ((co.co_filename.endswith('threading.py') and co.co_name.endswith('_bootstrap_inner')) or (self.state.frame.f_code.co_filename.endswith( os.path.join('multiprocessing', 'process.py')) and self.state.frame.f_code.co_name == '_bootstrap')): # Thread / Process is dead self.stop_trace() self.die() return if (event == 'call' and not self.stepping and not self.full and not continue_below and not self.get_file_breaks(frame.f_code.co_filename)): # Don't trace anymore here return return self.trace_dispatch
def trace_dispatch(self, frame, event, arg)
This function is called every line, function call, function return and exception during trace
4.367871
4.324721
1.009978
trace_log.info( 'Frame:%s. Event: %s. Arg: %r' % (pretty_frame(frame), event, arg) ) trace_log.debug( 'state %r breaks ? %s stops ? %s' % ( self.state, self.breaks(frame, no_remove=True), self.state.stops(frame, event) ) ) if event == 'return': trace_log.debug( 'Return: frame: %s, state: %s, state.f_back: %s' % ( pretty_frame(frame), pretty_frame(self.state.frame), pretty_frame(self.state.frame.f_back) ) ) if self.trace_dispatch(frame, event, arg): return self.trace_debug_dispatch trace_log.debug("No trace %s" % pretty_frame(frame))
def trace_debug_dispatch(self, frame, event, arg)
Utility function to add debug to tracing
3.938303
3.907854
1.007792
if self.tracing: return self.reset() log.info('Starting trace') frame = frame or sys._getframe().f_back # Setting trace without pausing self.set_trace(frame, break_=False) self.tracing = True self.below = below self.under = under self.full = full
def start_trace(self, full=False, frame=None, below=0, under=None)
Start tracing from here
4.733479
4.533912
1.044017
# We are already tracing, do nothing trace_log.info( 'Setting trace %s (stepping %s) (current_trace: %s)' % ( pretty_frame(frame or sys._getframe().f_back), self.stepping, sys.gettrace() ) ) if self.stepping or self.closed: return self.reset() trace = ( self.trace_dispatch if trace_log.level >= 30 else self.trace_debug_dispatch ) trace_frame = frame = frame or sys._getframe().f_back while frame: frame.f_trace = trace frame = frame.f_back self.state = Step(trace_frame) if break_ else Running(trace_frame) sys.settrace(trace)
def set_trace(self, frame=None, break_=True)
Break at current state
4.693017
4.697606
0.999023
self.tracing = False self.full = False frame = frame or sys._getframe().f_back while frame: del frame.f_trace frame = frame.f_back sys.settrace(None) log.info('Stopping trace')
def stop_trace(self, frame=None)
Stop tracing from here
3.660503
3.36798
1.086854
self.state = Until(frame, frame.f_lineno)
def set_until(self, frame, lineno=None)
Stop on the next line number.
13.447654
9.04128
1.487362
self.state = Running(frame) if not self.tracing and not self.breakpoints: # If we were in a set_trace and there's no breakpoint to trace for # Run without trace self.stop_trace()
def set_continue(self, frame)
Don't stop anymore
14.959404
12.949531
1.155208
log.info( 'Setting break fn:%s lno:%s tmp:%s cond:%s fun:%s' % (filename, lineno, temporary, cond, funcname) ) breakpoint = self.get_break( filename, lineno, temporary, cond, funcname ) self.breakpoints.add(breakpoint) log.info('Breakpoint %r added' % breakpoint) return breakpoint
def set_break( self, filename, lineno=None, temporary=False, cond=None, funcname=None )
Put a breakpoint for filename
3.294499
3.258224
1.011133
log.info( 'Removing break fn:%s lno:%s tmp:%s cond:%s fun:%s' % (filename, lineno, temporary, cond, funcname) ) breakpoint = self.get_break( filename, lineno, temporary or False, cond, funcname ) if temporary is None and breakpoint not in self.breakpoints: breakpoint = self.get_break(filename, lineno, True, cond, funcname) try: self.breakpoints.remove(breakpoint) log.info('Breakpoint %r removed' % breakpoint) except Exception: log.info('Breakpoint %r not removed: not found' % breakpoint)
def clear_break( self, filename, lineno=None, temporary=False, cond=None, funcname=None )
Remove a breakpoint
3.431522
3.307838
1.037391
try: return repr(obj) except Exception as e: return '??? Broken repr (%s: %s)' % (type(e).__name__, e)
def safe_repr(self, obj)
Like a repr but without exception
4.192169
3.872447
1.082563
context = context and dict(context) or {} recursion = id(obj) in context if not recursion: context[id(obj)] = obj try: rv = self.better_repr(obj, context, html, level + 1, full) except Exception: rv = None if rv: return rv self.obj_cache[id(obj)] = obj if html: return '<a href="%d" class="inspect">%s%s</a>' % ( id(obj), 'Recursion of ' if recursion else '', escape(self.safe_repr(obj)) ) return '%s%s' % ( 'Recursion of ' if recursion else '', self.safe_repr(obj) )
def safe_better_repr( self, obj, context=None, html=True, level=0, full=False )
Repr with inspect links on objects
3.333254
3.232248
1.031249
abbreviate = (lambda x, level, **kw: x) if full else cut_if_too_long def get_too_long_repr(ie): r = '[%d more…]' % ie.size if html: self.obj_cache[id(obj)] = obj return '<a href="dump/%d" class="inspect">%s</a>' % ( id(obj), r ) return r if isinstance(obj, dict): if isinstance(obj, OrderedDict): dict_sorted = lambda it, f: it else: dict_sorted = sorted dict_repr = ' ' * (level - 1) if type(obj) != dict: dict_repr = type(obj).__name__ + '({' closer = '})' else: dict_repr = '{' closer = '}' if len(obj) > 2: dict_repr += '\n' + ' ' * level if html: dict_repr += '''<table class=" mdl-data-table mdl-js-data-table mdl-data-table--selectable mdl-shadow--2dp">''' dict_repr += ''.join([ ( '<tr><td class="key">' + self.safe_repr(key) + ':' + '</td>' '<td class="val ' + 'mdl-data-table__cell--non-numeric">' + self.safe_better_repr( val, context, html, level, full ) + '</td></tr>' ) if not isinstance(key, IterableEllipsis) else ( '<tr><td colspan="2" class="ellipse">' + get_too_long_repr(key) + '</td></tr>' ) for key, val in abbreviate( dict_sorted(obj.items(), key=lambda x: x[0]), level, tuple_=True ) ]) dict_repr += '</table>' else: dict_repr += ('\n' + ' ' * level).join([ self.safe_repr(key) + ': ' + self.safe_better_repr(val, context, html, level, full) if not isinstance(key, IterableEllipsis) else get_too_long_repr(key) for key, val in abbreviate( dict_sorted(obj.items(), key=lambda x: x[0]), level, tuple_=True ) ]) closer = '\n' + ' ' * (level - 1) + closer else: dict_repr += ', '.join([ self.safe_repr(key) + ': ' + self.safe_better_repr(val, context, html, level, full) for key, val in dict_sorted(obj.items(), key=lambda x: x[0]) ]) dict_repr += closer return dict_repr if any([isinstance(obj, list), isinstance(obj, set), isinstance(obj, tuple)]): iter_repr = ' ' * (level - 1) if type(obj) == list: iter_repr = '[' closer = ']' elif type(obj) == set: iter_repr = '{' closer = '}' elif type(obj) == tuple: iter_repr = '(' closer = ')' else: iter_repr = escape(obj.__class__.__name__) + '([' closer = '])' splitter = ', ' if len(obj) > 2 and html: splitter += '\n' + ' ' * level iter_repr += '\n' + ' ' * level closer = '\n' + ' ' * (level - 1) + closer iter_repr += splitter.join([ self.safe_better_repr(val, context, html, level, full) if not isinstance(val, IterableEllipsis) else get_too_long_repr(val) for val in abbreviate(obj, level) ]) iter_repr += closer return iter_repr
def better_repr(self, obj, context=None, html=True, level=1, full=False)
Repr with html decorations or indentation
2.367898
2.37153
0.998468
self.hooked = '' def display_hook(obj): # That's some dirty hack self.hooked += self.safe_better_repr(obj) self.last_obj = obj stdout, stderr = sys.stdout, sys.stderr if with_hook: d_hook = sys.displayhook sys.displayhook = display_hook sys.stdout, sys.stderr = StringIO(), StringIO() out, err = [], [] try: yield out, err finally: out.extend(sys.stdout.getvalue().splitlines()) err.extend(sys.stderr.getvalue().splitlines()) if with_hook: sys.displayhook = d_hook sys.stdout, sys.stderr = stdout, stderr
def capture_output(self, with_hook=True)
Steal stream output, return them in string, restore them
3.135108
3.086927
1.015608
def safe_getattr(key): try: return getattr(thing, key) except Exception as e: return 'Error getting attr "%s" from "%s" (%s: %s)' % ( key, thing, type(e).__name__, e ) return dict(( escape(key), { 'val': self.safe_better_repr(safe_getattr(key)), 'type': type(safe_getattr(key)).__name__ } ) for key in dir(thing))
def dmp(self, thing)
Dump the content of an object in a dict for wdb.js
4.145342
4.001453
1.035959
import linecache # Hack for frozen importlib bootstrap if filename == '<frozen importlib._bootstrap>': filename = os.path.join( os.path.dirname(linecache.__file__), 'importlib', '_bootstrap.py' ) return to_unicode_string( ''.join(linecache.getlines(filename)), filename )
def get_file(self, filename)
Get file source from cache
6.299393
6.344815
0.992841
stack = [] if t and t.tb_frame == f: t = t.tb_next while f is not None: stack.append((f, f.f_lineno)) f = f.f_back stack.reverse() i = max(0, len(stack) - 1) while t is not None: stack.append((t.tb_frame, t.tb_lineno)) t = t.tb_next if f is None: i = max(0, len(stack) - 1) return stack, i
def get_stack(self, f, t)
Build the stack from frame and traceback
2.359196
2.060053
1.145211
import linecache frames = [] stack, _ = self.get_stack(frame, tb) current = 0 for i, (stack_frame, lno) in enumerate(stack): code = stack_frame.f_code filename = code.co_filename or '<unspecified>' line = None if filename[0] == '<' and filename[-1] == '>': line = get_source_from_byte_code(code) fn = filename else: fn = os.path.abspath(filename) if not line: linecache.checkcache(filename) line = linecache.getline(filename, lno, stack_frame.f_globals) if not line: line = self.compile_cache.get(id(code), '') line = to_unicode_string(line, filename) line = line and line.strip() startlnos = dis.findlinestarts(code) lastlineno = list(startlnos)[-1][1] if frame == stack_frame: current = i frames.append({ 'file': fn, 'function': code.co_name, 'flno': code.co_firstlineno, 'llno': lastlineno, 'lno': lno, 'code': line, 'level': i, 'current': frame == stack_frame }) # While in exception always put the context to the top return stack, frames, current
def get_trace(self, frame, tb)
Get a dict of the traceback for wdb.js use
4.182486
4.088464
1.022997
log.debug('Sending %s' % data) if not self._socket: log.warn('No connection') return self._socket.send_bytes(data.encode('utf-8'))
def send(self, data)
Send data through websocket
3.947353
3.640123
1.084401
log.debug('Receiving') if not self._socket: log.warn('No connection') return try: if timeout: rv = self._socket.poll(timeout) if not rv: log.info('Connection timeouted') return 'Quit' data = self._socket.recv_bytes() except Exception: log.error('Connection lost') return 'Quit' log.debug('Got %s' % data) return data.decode('utf-8')
def receive(self, timeout=None)
Receive data through websocket
3.967093
3.786549
1.047681
log.info( 'Interaction %r %r %r %r' % (frame, tb, exception, exception_description) ) self.reconnect_if_needed() self.stepping = not shell if not iframe_mode: opts = {} if shell: opts['type_'] = 'shell' if post_mortem: opts['type_'] = 'pm' self.open_browser(**opts) lvl = len(self.interaction_stack) if lvl: exception_description += ' [recursive%s]' % ( '^%d' % lvl if lvl > 1 else '' ) interaction = Interaction( self, frame, tb, exception, exception_description, init=init, shell=shell, shell_vars=shell_vars, source=source, timeout=timeout ) self.interaction_stack.append(interaction) # For meta debugging purpose self._ui = interaction if self.begun: # Each new state sends the trace and selects a frame interaction.init() else: self.begun = True interaction.loop() self.interaction_stack.pop() if lvl: self.interaction_stack[-1].init()
def interaction( self, frame, tb=None, exception='Wdb', exception_description='Stepping', init=None, shell=False, shell_vars=None, source=None, iframe_mode=False, timeout=None, post_mortem=False )
User interaction handling blocking on socket receive
4.62004
4.532458
1.019323
fun = frame.f_code.co_name log.info('Calling: %r' % fun) init = 'Echo|%s' % dump({ 'for': '__call__', 'val': '%s(%s)' % ( fun, ', '.join([ '%s=%s' % (key, self.safe_better_repr(value)) for key, value in get_args(frame).items() ]) ) }) self.interaction( frame, init=init, exception_description='Calling %s' % fun )
def handle_call(self, frame, argument_list)
This method is called when there is the remote possibility that we ever need to stop in this function.
7.349651
7.327668
1.003
log.info('Stopping at line %s' % pretty_frame(frame)) self.interaction(frame)
def handle_line(self, frame, arg)
This function is called when we stop or break at this line.
17.361759
12.811
1.355223
self.obj_cache[id(return_value)] = return_value self.extra_vars['__return__'] = return_value fun = frame.f_code.co_name log.info('Returning from %r with value: %r' % (fun, return_value)) init = 'Echo|%s' % dump({ 'for': '__return__', 'val': self.safe_better_repr(return_value) }) self.interaction( frame, init=init, exception_description='Returning from %s with value %s' % (fun, return_value) )
def handle_return(self, frame, return_value)
This function is called when a return trap is set here.
6.280106
6.105074
1.02867
type_, value, tb = exc_info # Python 3 is broken see http://bugs.python.org/issue17413 _value = value if not isinstance(_value, BaseException): _value = type_(value) fake_exc_info = type_, _value, tb log.error('Exception during trace', exc_info=fake_exc_info) self.obj_cache[id(exc_info)] = exc_info self.extra_vars['__exception__'] = exc_info exception = type_.__name__ exception_description = str(value) init = 'Echo|%s' % dump({ 'for': '__exception__', 'val': escape('%s: %s') % (exception, exception_description) }) # User exception is 4 frames away from exception frame = frame or sys._getframe().f_back.f_back.f_back.f_back self.interaction( frame, tb, exception, exception_description, init=init )
def handle_exception(self, frame, exc_info)
This function is called if an exception occurs, but only if we are to stop at or just below this level.
5.924573
6.02658
0.983074
for breakpoint in set(self.breakpoints): if breakpoint.breaks(frame): if breakpoint.temporary and not no_remove: self.breakpoints.remove(breakpoint) return True return False
def breaks(self, frame, no_remove=False)
Return True if there's a breakpoint at frame
3.794252
3.503918
1.08286
return [ breakpoint for breakpoint in self.breakpoints if breakpoint.on_file(filename) ]
def get_file_breaks(self, filename)
List all file `filename` breakpoints
8.117448
6.374948
1.273336
return list( filter( lambda x: x is not None, [ getattr(breakpoint, 'line', None) for breakpoint in self.breakpoints if breakpoint.on_file(filename) ] ) )
def get_breaks_lno(self, filename)
List all line numbers that have a breakpoint
4.370475
3.446418
1.268121
log.info('Time to die') if self.connected: try: self.send('Die') except Exception: pass if self._socket: self._socket.close() self.pop()
def die(self)
Time to quit
6.415954
5.810919
1.10412
assert name not in self._processes, "process names must be unique" proc = self._process_ctor(cmd, name=name, quiet=quiet, colour=next(self._colours), env=env, cwd=cwd) self._processes[name] = {} self._processes[name]['obj'] = proc # Update printer width to accommodate this process name self._printer.width = max(self._printer.width, len(name)) return proc
def add_process(self, name, cmd, quiet=False, env=None, cwd=None)
Add a process to this manager instance. The process will not be started until :func:`~honcho.manager.Manager.loop` is called.
3.985784
4.113002
0.969069
def _terminate(signum, frame): self._system_print("%s received\n" % SIGNALS[signum]['name']) self.returncode = SIGNALS[signum]['rc'] self.terminate() signal.signal(signal.SIGTERM, _terminate) signal.signal(signal.SIGINT, _terminate) self._start() exit = False exit_start = None while 1: try: msg = self.events.get(timeout=0.1) except Empty: if exit: break else: if msg.type == 'line': self._printer.write(msg) elif msg.type == 'start': self._processes[msg.name]['pid'] = msg.data['pid'] self._system_print("%s started (pid=%s)\n" % (msg.name, msg.data['pid'])) elif msg.type == 'stop': self._processes[msg.name]['returncode'] = msg.data['returncode'] self._system_print("%s stopped (rc=%s)\n" % (msg.name, msg.data['returncode'])) if self.returncode is None: self.returncode = msg.data['returncode'] if self._all_started() and self._all_stopped(): exit = True if exit_start is None and self._all_started() and self._any_stopped(): exit_start = self._env.now() self.terminate() if exit_start is not None: # If we've been in this loop for more than KILL_WAIT seconds, # it's time to kill all remaining children. waiting = self._env.now() - exit_start if waiting > datetime.timedelta(seconds=KILL_WAIT): self.kill()
def loop(self)
Start all the added processes and multiplex their output onto the bound printer (which by default will print to STDOUT). If one process terminates, all the others will be terminated by Honcho, and :func:`~honcho.manager.Manager.loop` will return. This method will block until all the processes have terminated.
2.820232
2.864325
0.984606
for_termination = [] for n, p in iteritems(self._processes): if 'returncode' not in p: for_termination.append(n) for n in for_termination: p = self._processes[n] signame = 'SIGKILL' if force else 'SIGTERM' self._system_print("sending %s to %s (pid %s)\n" % (signame, n, p['pid'])) if force: self._env.kill(p['pid']) else: self._env.terminate(p['pid'])
def _killall(self, force=False)
Kill all remaining processes, forcefully if requested.
3.752277
3.623862
1.035436
values = {} for line in content.splitlines(): lexer = shlex.shlex(line, posix=True) tokens = list(lexer) # parses the assignment statement if len(tokens) < 3: continue name, op = tokens[:2] value = ''.join(tokens[2:]) if op != '=': continue if not re.match(r'[A-Za-z_][A-Za-z_0-9]*', name): continue value = value.replace(r'\n', '\n') value = value.replace(r'\t', '\t') values[name] = value return values
def parse(content)
Parse the content of a .env file (a line-delimited KEY=value format) into a dictionary mapping keys to values.
2.679026
2.608424
1.027067
if env is not None and env.get("PORT") is not None: port = int(env.get("PORT")) if quiet is None: quiet = [] con = defaultdict(lambda: 1) if concurrency is not None: con.update(concurrency) out = [] for name, cmd in compat.iteritems(processes): for i in range(con[name]): n = "{0}.{1}".format(name, i + 1) c = cmd q = name in quiet e = {'HONCHO_PROCESS_NAME': n} if env is not None: e.update(env) if port is not None: e['PORT'] = str(port + i) params = ProcessParams(n, c, q, e) out.append(params) if port is not None: port += 100 return out
def expand_processes(processes, concurrency=None, env=None, quiet=None, port=None)
Get a list of the processes that need to be started given the specified list of process types, concurrency, environment, quietness, and base port number. Returns a list of ProcessParams objects, which have `name`, `cmd`, `env`, and `quiet` attributes, corresponding to the parameters to the constructor of `honcho.process.Process`.
3.314176
2.832216
1.170171
patt = re.compile(r'\W', re.UNICODE) return re.sub(patt, '-', value)
def dashrepl(value)
Replace any non-word characters with a dash.
4.019563
2.867944
1.401549
for root, dirs, files in os.walk(static_dir): for filename in files: if cls._pattern.match(filename): APPS_INCLUDE_DIRS.append(static_dir) return
def traverse_tree(cls, static_dir)
traverse the static folders an look for at least one file ending in .scss/.sass
4.639054
4.279216
1.08409
app_configs = apps.get_app_configs() for app_config in app_configs: ignore_dirs = [] for root, dirs, files in os.walk(app_config.path): if [True for idir in ignore_dirs if root.startswith(idir)]: continue if '__init__.py' not in files: ignore_dirs.append(root) continue for filename in files: basename, ext = os.path.splitext(filename) if ext != '.py': continue yield os.path.abspath(os.path.join(root, filename))
def find_sources(self)
Look for Python sources available for the current configuration.
2.40705
2.321547
1.03683
callvisitor = FuncCallVisitor('sass_processor') tree = ast.parse(open(filename, 'rb').read()) callvisitor.visit(tree) for sass_fileurl in callvisitor.sass_files: sass_filename = find_file(sass_fileurl) if not sass_filename or sass_filename in self.processed_files: continue if self.delete_files: self.delete_file(sass_filename, sass_fileurl) else: self.compile_sass(sass_filename, sass_fileurl)
def parse_source(self, filename)
Extract the statements from the given file, look for function calls `sass_processor(scss_file)` and compile the filename into CSS.
4.127904
3.205739
1.287661