def _exec_file(self, fname): try: full_filename = filefind(fname, [u'.', self.ipython_dir]) except IOError as e: self.log.warn("File not found: %r" % fname) return # Make sure that the running script gets a proper sys.argv as if it # were run from a system shell. save_argv = sys.argv sys.argv = [full_filename] + self.extra_args[1:] # protect sys.argv from potential unicode strings on Python 2: if not py3compat.PY3: sys.argv = [py3compat.cast_bytes(a) for a in sys.argv] try: if os.path.isfile(full_filename): if full_filename.endswith('.ipy'): self.log.info("Running file in user namespace: %s" % full_filename) self.shell.safe_execfile_ipy(full_filename) else: # default to python, even without extension self.log.info("Running file in user namespace: %s" % full_filename) # Ensure that __file__ is always defined to match Python behavior self.shell.user_ns['__file__'] = fname try: self.shell.safe_execfile(full_filename, self.shell.user_ns) finally: del self.shell.user_ns['__file__'] finally: sys.argv = save_argv
def complete_request(self, text): line = str_to_unicode(readline.get_line_buffer()) byte_cursor_pos = readline.get_endidx() # get_endidx is a byte offset # account for multi-byte characters to get correct cursor_pos bytes_before_cursor = cast_bytes(line)[:byte_cursor_pos] cursor_pos = len(cast_unicode(bytes_before_cursor)) # send completion request to kernel # Give the kernel up to 5s to respond msg_id = self.client.complete( code=line, cursor_pos=cursor_pos, ) msg = self.client.shell_channel.get_msg(timeout=self.timeout) if msg['parent_header']['msg_id'] == msg_id: content = msg['content'] cursor_start = content['cursor_start'] matches = [ line[:cursor_start] + m for m in content['matches'] ] if content["cursor_end"] < cursor_pos: extra = line[content["cursor_end"]: cursor_pos] matches = [m + extra for m in matches] matches = [ unicode_to_str(m) for m in matches ] return matches return []
def pandoc(source, fmt, to, extra_args=None, encoding='utf-8'): """Convert an input string in format `from` to format `to` via pandoc. Parameters ---------- source : string Input string, assumed to be valid format `from`. fmt : string The name of the input format (markdown, etc.) to : string The name of the output format (html, etc.) Returns ------- out : unicode Output as returned by pandoc. Exceptions ---------- This function will raise PandocMissing if pandoc is not installed. Any error messages generated by pandoc are printed to stderr. """ cmd = ['pandoc', '-f', fmt, '-t', to] if extra_args: cmd.extend(extra_args) # this will raise an exception that will pop us out of here check_pandoc_version() # we can safely continue p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE) out, _ = p.communicate(cast_bytes(source, encoding)) out = TextIOWrapper(BytesIO(out), encoding, 'replace').read() return out.rstrip('\n')
def pandoc(source, fmt, to, extra_args=None, encoding='utf-8'): """Convert an input string in format `from` to format `to` via pandoc. This function will raise an error if pandoc is not installed. Any error messages generated by pandoc are printed to stderr. Parameters ---------- source : string Input string, assumed to be valid format `from`. fmt : string The name of the input format (markdown, etc.) to : string The name of the output format (html, etc.) Returns ------- out : unicode Output as returned by pandoc. """ command = ['pandoc', '-f', fmt, '-t', to] if extra_args: command.extend(extra_args) try: p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE ) except OSError: sys.exit("ERROR: Unable to launch pandoc. Please install pandoc:\n" "(http://johnmacfarlane.net/pandoc/installing.html)") out, _ = p.communicate(cast_bytes(source, encoding)) out = out.decode(encoding, 'replace') return out[:-1]
def complete_request(self, text): line = str_to_unicode(readline.get_line_buffer()) byte_cursor_pos = readline.get_endidx() # get_endidx is a byte offset # account for multi-byte characters to get correct cursor_pos bytes_before_cursor = cast_bytes(line)[:byte_cursor_pos] cursor_pos = len(cast_unicode(bytes_before_cursor)) # send completion request to kernel # Give the kernel up to 5s to respond msg_id = self.client.complete( code=line, cursor_pos=cursor_pos, ) msg = self.client.shell_channel.get_msg(timeout=self.timeout) if msg['parent_header']['msg_id'] == msg_id: content = msg['content'] cursor_start = content['cursor_start'] matches = [line[:cursor_start] + m for m in content['matches']] if content["cursor_end"] < cursor_pos: extra = line[content["cursor_end"]:cursor_pos] matches = [m + extra for m in matches] matches = [unicode_to_str(m) for m in matches] return matches return []
def transform_cell(self, cell, resources, cell_index): """ Apply a transformation on each cell, Parameters ---------- cell : NotebookNode cell Notebook cell being processed resources : dictionary Additional resources used in the conversion process. Allows transformers to pass variables into the Jinja engine. cell_index : int Index of the cell being processed (see base.py) """ #Get the unique key from the resource dict if it exists. If it does not #exist, use 'figure' as the default. unique_key = resources.get('unique_key', 'figure') #Make sure figures key exists if not 'figures' in resources: resources['figures'] = {} #Loop through all of the outputs in the cell for index, out in enumerate(cell.get('outputs', [])): #Get the output in data formats that the template is interested in. for out_type in self.display_data_priority: if out.hasattr(out_type): data = out[out_type] #Binary files are base64-encoded, SVG is already XML if out_type in ('png', 'jpg', 'jpeg', 'pdf'): # data is b64-encoded as text (str, unicode) # decodestring only accepts bytes data = py3compat.cast_bytes(data) data = base64.decodestring(data) elif sys.platform == 'win32': data = data.replace('\n', '\r\n').encode("UTF-8") else: data = data.encode("UTF-8") #Build a figure name figure_name = self.figure_filename_template.format( unique_key=unique_key, cell_index=cell_index, index=index, extension=out_type) #On the cell, make the figure available via # cell.outputs[i].svg_filename ... etc (svg in example) # Where # cell.outputs[i].svg contains the data out[out_type + '_filename'] = figure_name #In the resources, make the figure available via # resources['figures']['filename'] = data resources['figures'][figure_name] = data return cell, resources
def respond_zip(handler, name, output, resources): """Zip up the output and resource files and respond with the zip file. Returns True if it has served a zip file, False if there are no resource files, in which case we serve the plain output file. """ # Check if we have resource files we need to zip output_files = resources.get('outputs', None) if not output_files: return False # Headers zip_filename = os.path.splitext(name)[0] + '.zip' handler.set_header('Content-Disposition', 'attachment; filename="%s"' % zip_filename) handler.set_header('Content-Type', 'application/zip') # Prepare the zip file buffer = io.BytesIO() zipf = zipfile.ZipFile(buffer, mode='w', compression=zipfile.ZIP_DEFLATED) output_filename = os.path.splitext(name)[0] + '.' + resources['output_extension'] zipf.writestr(output_filename, cast_bytes(output, 'utf-8')) for filename, data in output_files.items(): zipf.writestr(os.path.basename(filename), data) zipf.close() handler.finish(buffer.getvalue()) return True
def shlex_split(x): """Helper function to split lines into segments. """ # shlex.split raises an exception if there is a syntax error in sh syntax # for example if no closing " is found. This function keeps dropping the # last character of the line until shlex.split does not raise # an exception. It adds end of the line to the result of shlex.split # # Example: # %run "c:/python -> ['%run','"c:/python'] # shlex.split has unicode bugs in Python 2, so encode first to str if not py3compat.PY3: x = py3compat.cast_bytes(x) endofline = [] while x != '': try: comps = shlex.split(x) if len(endofline) >= 1: comps.append(''.join(endofline)) return comps except ValueError: endofline = [x[-1:]]+endofline x = x[:-1] return [''.join(endofline)]
def _exec_file(self, fname): try: full_filename = filefind(fname, [u'.', self.ipython_dir]) except IOError as e: self.log.warn("File not found: %r"%fname) return # Make sure that the running script gets a proper sys.argv as if it # were run from a system shell. save_argv = sys.argv sys.argv = [full_filename] + self.extra_args[1:] # protect sys.argv from potential unicode strings on Python 2: if not py3compat.PY3: sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ] try: if os.path.isfile(full_filename): if full_filename.endswith('.ipy'): self.log.info("Running file in user namespace: %s" % full_filename) self.shell.safe_execfile_ipy(full_filename) else: # default to python, even without extension self.log.info("Running file in user namespace: %s" % full_filename) # Ensure that __file__ is always defined to match Python behavior self.shell.user_ns['__file__'] = fname try: self.shell.safe_execfile(full_filename, self.shell.user_ns) finally: del self.shell.user_ns['__file__'] finally: sys.argv = save_argv
def shlex_split(x): """Helper function to split lines into segments. """ # shlex.split raises an exception if there is a syntax error in sh syntax # for example if no closing " is found. This function keeps dropping the # last character of the line until shlex.split does not raise # an exception. It adds end of the line to the result of shlex.split # # Example: # %run "c:/python -> ['%run','"c:/python'] # shlex.split has unicode bugs in Python 2, so encode first to str if not py3compat.PY3: x = py3compat.cast_bytes(x) endofline = [] while x != '': try: comps = shlex.split(x) if len(endofline) >= 1: comps.append(''.join(endofline)) return comps except ValueError: endofline = [x[-1:]] + endofline x = x[:-1] return [''.join(endofline)]
def load_connector_file(self): """load config from a JSON connector file, at a *lower* priority than command-line/config files. """ self.log.info("Loading url_file %r", self.url_file) config = self.config with open(self.url_file) as f: d = json.loads(f.read()) if 'exec_key' in d: config.Session.key = cast_bytes(d['exec_key']) try: config.EngineFactory.location except AttributeError: config.EngineFactory.location = d['location'] d['url'] = disambiguate_url(d['url'], config.EngineFactory.location) try: config.EngineFactory.url except AttributeError: config.EngineFactory.url = d['url'] try: config.EngineFactory.sshserver except AttributeError: config.EngineFactory.sshserver = d['ssh']
def pandoc(source, fmt, to, extra_args=None, encoding='utf-8'): """Convert an input string in format `from` to format `to` via pandoc. This function will raise an error if pandoc is not installed. Any error messages generated by pandoc are printed to stderr. Parameters ---------- source : string Input string, assumed to be valid format `from`. fmt : string The name of the input format (markdown, etc.) to : string The name of the output format (html, etc.) Returns ------- out : unicode Output as returned by pandoc. """ command = ['pandoc', '-f', fmt, '-t', to] if extra_args: command.extend(extra_args) try: p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE) except OSError as e: raise PandocMissing("The command '%s' returned an error: %s.\n" % (" ".join(command), e) + "Please check that pandoc package is installed.") out, _ = p.communicate(cast_bytes(source, encoding)) out = TextIOWrapper(BytesIO(out), encoding, 'replace').read() return out.rstrip('\n')
def dispatch_notification(self, msg): """dispatch register/unregister events.""" try: idents, msg = self.session.feed_identities(msg) except ValueError: self.log.warn("task::Invalid Message: %r", msg) return try: msg = self.session.unserialize(msg) except ValueError: self.log.warn("task::Unauthorized message from: %r" % idents) return msg_type = msg['header']['msg_type'] handler = self._notification_handlers.get(msg_type, None) if handler is None: self.log.error("Unhandled message type: %r" % msg_type) else: try: handler(cast_bytes(msg['content']['uuid'])) except Exception: self.log.error("task::Invalid notification msg: %r", msg, exc_info=True)
def pandoc(source, fmt, to, extra_args=None, encoding="utf-8"): """Convert an input string in format `from` to format `to` via pandoc. This function will raise an error if pandoc is not installed. Any error messages generated by pandoc are printed to stderr. Parameters ---------- source : string Input string, assumed to be valid format `from`. fmt : string The name of the input format (markdown, etc.) to : string The name of the output format (html, etc.) Returns ------- out : unicode Output as returned by pandoc. """ command = ["pandoc", "-f", fmt, "-t", to] if extra_args: command.extend(extra_args) try: p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE) except OSError as e: raise PandocMissing( "The command '%s' returned an error: %s.\n" % (" ".join(command), e) + "Please check that pandoc is installed:\n" + "http://johnmacfarlane.net/pandoc/installing.html" ) out, _ = p.communicate(cast_bytes(source, encoding)) out = TextIOWrapper(BytesIO(out), encoding, "replace").read() return out.rstrip("\n")
def pandoc(source, fmt, to, encoding='utf-8'): """Convert an input string in format `from` to format `to` via pandoc. This function will raise an error if pandoc is not installed. Any error messages generated by pandoc are printed to stderr. Parameters ---------- source : string Input string, assumed to be valid format `from`. fmt : string The name of the input format (markdown, etc.) to : string The name of the output format (html, etc.) Returns ------- out : unicode Output as returned by pandoc. """ p = subprocess.Popen(['pandoc', '-f', fmt, '-t', to], stdin=subprocess.PIPE, stdout=subprocess.PIPE ) out, _ = p.communicate(cast_bytes(source, encoding)) out = out.decode(encoding, 'replace') return out[:-1]
def base64_decode(s): """unicode-safe base64 base64 API only talks bytes """ s = py3compat.cast_bytes(s) decoded = base64.decodestring(s) return decoded
def base64_decode(s): """unicode-safe base64 base64 API only talks bytes """ s = py3compat.cast_bytes(s) decoded = decodebytes(s) return decoded
def base64_encode(s): """unicode-safe base64 base64 API only talks bytes """ s = py3compat.cast_bytes(s) encoded = encodebytes(s) return encoded.decode('ascii')
def base64_encode(s): """unicode-safe base64 base64 API only talks bytes """ s = py3compat.cast_bytes(s) encoded = base64.encodestring(s) return encoded.decode('ascii')
def _topic(self, topic): """prefixed topic for IOPub messages""" if self.int_id >= 0: base = "engine.%i" % self.int_id else: base = "kernel.%s" % self.ident return py3compat.cast_bytes("%s.%s" % (base, topic))
def passwd_check(hashed_passphrase, passphrase): """Verify that a given passphrase matches its hashed version. Parameters ---------- hashed_passphrase : str Hashed password, in the format returned by `passwd`. passphrase : str Passphrase to validate. Returns ------- valid : bool True if the passphrase matches the hash. Examples -------- In [1]: from IPython.lib.security import passwd_check In [2]: passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a', ...: 'mypassword') Out[2]: True In [3]: passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a', ...: 'anotherpassword') Out[3]: False """ try: algorithm, salt, pw_digest = hashed_passphrase.split(':', 2) except (ValueError, TypeError): return False try: h = hashlib.new(algorithm) except ValueError: return False if len(pw_digest) == 0: return False h.update(cast_bytes(passphrase, 'utf-8') + cast_bytes(salt, 'ascii')) return h.hexdigest() == pw_digest
def save_task_result(self, idents, msg): """save the result of a completed task.""" client_id = idents[0] try: msg = self.session.unserialize(msg) except Exception: self.log.error("task::invalid task result message send to %r: %r", client_id, msg, exc_info=True) return parent = msg['parent_header'] if not parent: # print msg self.log.warn("Task %r had no parent!", msg) return msg_id = parent['msg_id'] if msg_id in self.unassigned: self.unassigned.remove(msg_id) header = msg['header'] engine_uuid = header.get('engine', u'') eid = self.by_ident.get(cast_bytes(engine_uuid), None) status = header.get('status', None) if msg_id in self.pending: self.log.info("task::task %r finished on %s", msg_id, eid) self.pending.remove(msg_id) self.all_completed.add(msg_id) if eid is not None: if status != 'aborted': self.completed[eid].append(msg_id) if msg_id in self.tasks[eid]: self.tasks[eid].remove(msg_id) completed = header['date'] started = header.get('started', None) result = { 'result_header' : header, 'result_content': msg['content'], 'started' : started, 'completed' : completed, 'received' : datetime.now(), 'engine_uuid': engine_uuid, } result['result_buffers'] = msg['buffers'] try: self.db.update_record(msg_id, result) except Exception: self.log.error("DB Error saving task request %r", msg_id, exc_info=True) else: self.log.debug("task::unknown task %r finished", msg_id)
def save_task_result(self, idents, msg): """save the result of a completed task.""" client_id = idents[0] try: msg = self.session.unserialize(msg) except Exception: self.log.error("task::invalid task result message send to %r: %r", client_id, msg, exc_info=True) return parent = msg["parent_header"] if not parent: # print msg self.log.warn("Task %r had no parent!", msg) return msg_id = parent["msg_id"] if msg_id in self.unassigned: self.unassigned.remove(msg_id) header = msg["header"] engine_uuid = header.get("engine", u"") eid = self.by_ident.get(cast_bytes(engine_uuid), None) status = header.get("status", None) if msg_id in self.pending: self.log.info("task::task %r finished on %s", msg_id, eid) self.pending.remove(msg_id) self.all_completed.add(msg_id) if eid is not None: if status != "aborted": self.completed[eid].append(msg_id) if msg_id in self.tasks[eid]: self.tasks[eid].remove(msg_id) completed = header["date"] started = header.get("started", None) result = { "result_header": header, "result_content": msg["content"], "started": started, "completed": completed, "received": datetime.now(), "engine_uuid": engine_uuid, } result["result_buffers"] = msg["buffers"] try: self.db.update_record(msg_id, result) except Exception: self.log.error("DB Error saving task request %r", msg_id, exc_info=True) else: self.log.debug("task::unknown task %r finished", msg_id)
def markdown2html_marked(source, encoding="utf-8"): """Convert a markdown string to HTML via marked""" command = [_find_nodejs(), marked] try: p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE) except OSError as e: raise NodeJSMissing( "The command '%s' returned an error: %s.\n" % (" ".join(command), e) + "Please check that Node.js is installed." ) out, _ = p.communicate(cast_bytes(source, encoding)) out = TextIOWrapper(BytesIO(out), encoding, "replace").read() return out.rstrip("\n")
def signup(): form = SignUpForm(request.form, csrf_enabled=False) if request.method == 'POST': if form.validate(): username = str(form.username.data) email = str(form.email.data) password = str(form.password.data) #curr user count curr_user_count = models.User.query.count() if curr_user_count >= 15: flash( 'Your company can only create 15 users, please contact us if you have any question' ) return render_template('index.html') # get the next server port port = 9499 + curr_user_count + 1 #create passwd h = hashlib.new(algorithm) salt = ('%0' + str(salt_len) + 'x') % random.getrandbits( 4 * salt_len) h.update( cast_bytes(password, 'utf-8') + str_to_bytes(salt, 'ascii')) hashed_password = '******'.join((algorithm, salt, h.hexdigest())) # create user user = models.User() user.username = username user.email = email user.password = hashed_password user.nbserver_port = port user = db.session.merge(user) db.session.commit() # create the user data directory hierarchy if not os.path.exists('{0}/{1}'.format(DATA_DIR, username)): create_user_dir(username, hashed_password) return redirect('/login') else: errorMsg = '' for key in form.errors: errorMsg = errorMsg + key + ':' + form.errors[key][0] + ' ' flash(errorMsg) return render_template('index.html') return render_template('index.html')
def markdown2html_marked(source, encoding='utf-8'): """Convert a markdown string to HTML via marked""" command = [_find_nodejs(), marked] try: p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE) except OSError as e: raise NodeJSMissing("The command '%s' returned an error: %s.\n" % (" ".join(command), e) + "Please check that Node.js is installed.") out, _ = p.communicate(cast_bytes(source, encoding)) out = TextIOWrapper(BytesIO(out), encoding, 'replace').read() return out.rstrip('\n')
def getlines(filename, module_globals=None): """Get the lines (as unicode) for a file from the cache. Update the cache if it doesn't contain an entry for this file already.""" filename = py3compat.cast_bytes(filename, sys.getfilesystemencoding()) lines = linecache.getlines(filename, module_globals=module_globals) if (not lines) or isinstance(lines[0], str): return lines readline = openpy._list_readline(lines) try: encoding, _ = openpy.detect_encoding(readline) except SyntaxError: encoding = 'ascii' return [l.decode(encoding, 'replace') for l in lines]
def __init__(self, session, pub_socket, name, pipe=True): self.encoding = 'UTF-8' self.session = session self.pub_socket = pub_socket self.name = name self.topic = b'stream.' + py3compat.cast_bytes(name) self.parent_header = {} self._new_buffer() self._buffer_lock = threading.Lock() self._master_pid = os.getpid() self._master_thread = threading.current_thread().ident self._pipe_pid = os.getpid() self._pipe_flag = pipe if pipe: self._setup_pipe_in()
def getlines(filename, module_globals=None): """Get the lines (as unicode) for a file from the cache. Update the cache if it doesn't contain an entry for this file already.""" filename = py3compat.cast_bytes(filename, sys.getfilesystemencoding()) lines = linecache.getlines(filename, module_globals=module_globals) # The bits we cache ourselves can be unicode. if (not lines) or isinstance(lines[0], unicode): return lines readline = openpy._list_readline(lines) try: encoding, _ = openpy.detect_encoding(readline) except SyntaxError: encoding = 'ascii' return [l.decode(encoding, 'replace') for l in lines]
def dispatch_query_reply(self, msg): """handle reply to our initial connection request""" try: idents,msg = self.session.feed_identities(msg) except ValueError: self.log.warn("task::Invalid Message: %r",msg) return try: msg = self.session.unserialize(msg) except ValueError: self.log.warn("task::Unauthorized message from: %r"%idents) return content = msg['content'] for uuid in content.get('engines', {}).values(): self._register_engine(cast_bytes(uuid))
def dispatch_query_reply(self, msg): """handle reply to our initial connection request""" try: idents, msg = self.session.feed_identities(msg) except ValueError: self.log.warn("task::Invalid Message: %r", msg) return try: msg = self.session.unserialize(msg) except ValueError: self.log.warn("task::Unauthorized message from: %r" % idents) return content = msg['content'] for uuid in content.get('engines', {}).values(): self._register_engine(cast_bytes(uuid))
def signup(): form = SignUpForm(request.form,csrf_enabled=False) if request.method == 'POST': if form.validate(): username = str(form.username.data) email = str(form.email.data) password = str(form.password.data) #curr user count curr_user_count = models.User.query.count() if curr_user_count >= 15: flash('Your company can only create 15 users, please contact us if you have any question') return render_template('index.html') # get the next server port port = 9499 + curr_user_count + 1 #create passwd h = hashlib.new(algorithm) salt = ('%0' + str(salt_len) + 'x') % random.getrandbits(4 * salt_len) h.update(cast_bytes(password, 'utf-8') + str_to_bytes(salt, 'ascii')) hashed_password = '******'.join((algorithm, salt, h.hexdigest())) # create user user = models.User() user.username = username user.email = email user.password = hashed_password user.nbserver_port = port user = db.session.merge(user) db.session.commit() # create the user data directory hierarchy if not os.path.exists('{0}/{1}'.format(DATA_DIR, username)): create_user_dir(username, hashed_password) return redirect('/login') else: errorMsg = '' for key in form.errors: errorMsg=errorMsg+key+':'+form.errors[key][0]+' ' flash(errorMsg) return render_template('index.html') return render_template('index.html')
def load_connector_file(self): """load config from a JSON connector file, at a *lower* priority than command-line/config files. """ self.log.info("Loading url_file %r", self.url_file) config = self.config with open(self.url_file) as f: num_tries = 0 max_tries = 5 d = "" while not d: try: d = json.loads(f.read()) except ValueError: if num_tries > max_tries: raise num_tries += 1 time.sleep(0.5) # allow hand-override of location for disambiguation # and ssh-server if 'EngineFactory.location' not in config: config.EngineFactory.location = d['location'] if 'EngineFactory.sshserver' not in config: config.EngineFactory.sshserver = d.get('ssh') location = config.EngineFactory.location proto, ip = d['interface'].split('://') ip = disambiguate_ip_address(ip, location) d['interface'] = '%s://%s' % (proto, ip) # DO NOT allow override of basic URLs, serialization, or key # JSON file takes top priority there config.Session.key = cast_bytes(d['key']) config.Session.signature_scheme = d['signature_scheme'] config.EngineFactory.url = d['interface'] + ':%i' % d['registration'] config.Session.packer = d['pack'] config.Session.unpacker = d['unpack'] self.log.debug("Config changed:") self.log.debug("%r", config) self.connection_info = d
def passwd(passphrase=None, algorithm='sha1'): """Generate hashed password and salt for use in notebook configuration. In the notebook configuration, set `c.NotebookApp.password` to the generated string. Parameters ---------- passphrase : str Password to hash. If unspecified, the user is asked to input and verify a password. algorithm : str Hashing algorithm to use (e.g, 'sha1' or any argument supported by :func:`hashlib.new`). Returns ------- hashed_passphrase : str Hashed password, in the format 'hash_algorithm:salt:passphrase_hash'. Examples -------- >>> passwd('mypassword') 'sha1:7cf3:b7d6da294ea9592a9480c8f52e63cd42cfb9dd12' """ if passphrase is None: for i in range(3): p0 = getpass.getpass('Enter password: '******'Verify password: '******'Passwords do not match.') else: raise UsageError('No matching passwords found. Giving up.') h = hashlib.new(algorithm) salt = ('%0' + str(salt_len) + 'x') % random.getrandbits(4 * salt_len) h.update(cast_bytes(passphrase, 'utf-8') + str_to_bytes(salt, 'ascii')) return ':'.join((algorithm, salt, h.hexdigest()))
def yield_everything(obj): """Yield every item in a container as bytes Allows any JSONable object to be passed to an HMAC digester without having to serialize the whole thing. """ if isinstance(obj, dict): for key in sorted(obj): value = obj[key] yield cast_bytes(key) for b in yield_everything(value): yield b elif isinstance(obj, (list, tuple)): for element in obj: for b in yield_everything(element): yield b elif isinstance(obj, unicode_type): yield obj.encode('utf8') else: yield unicode_type(obj).encode('utf8')
def load_connector_file(self): """load config from a JSON connector file, at a *lower* priority than command-line/config files. """ self.log.info("Loading url_file %r", self.url_file) config = self.config with open(self.url_file) as f: d = json.loads(f.read()) # allow hand-override of location for disambiguation # and ssh-server try: config.EngineFactory.location except AttributeError: config.EngineFactory.location = d['location'] try: config.EngineFactory.sshserver except AttributeError: config.EngineFactory.sshserver = d.get('ssh') location = config.EngineFactory.location proto, ip = d['interface'].split('://') ip = disambiguate_ip_address(ip, location) d['interface'] = '%s://%s' % (proto, ip) # DO NOT allow override of basic URLs, serialization, or exec_key # JSON file takes top priority there config.Session.key = cast_bytes(d['exec_key']) config.EngineFactory.url = d['interface'] + ':%i' % d['registration'] config.Session.packer = d['pack'] config.Session.unpacker = d['unpack'] self.log.debug("Config changed:") self.log.debug("%r", config) self.connection_info = d
def load_connector_file(self): """load config from a JSON connector file, at a *lower* priority than command-line/config files. """ self.log.info("Loading url_file %r", self.url_file) config = self.config with open(self.url_file) as f: d = json.loads(f.read()) # allow hand-override of location for disambiguation # and ssh-server try: config.EngineFactory.location except AttributeError: config.EngineFactory.location = d["location"] try: config.EngineFactory.sshserver except AttributeError: config.EngineFactory.sshserver = d.get("ssh") location = config.EngineFactory.location proto, ip = d["interface"].split("://") ip = disambiguate_ip_address(ip, location) d["interface"] = "%s://%s" % (proto, ip) # DO NOT allow override of basic URLs, serialization, or exec_key # JSON file takes top priority there config.Session.key = cast_bytes(d["exec_key"]) config.EngineFactory.url = d["interface"] + ":%i" % d["registration"] config.Session.packer = d["pack"] config.Session.unpacker = d["unpack"] self.log.debug("Config changed:") self.log.debug("%r", config) self.connection_info = d
def _validate_targets(self, targets): """turn any valid targets argument into a list of integer ids""" if targets is None: # default to all return self.ids if isinstance(targets, (int,str,unicode)): # only one target specified targets = [targets] _targets = [] for t in targets: # map raw identities to ids if isinstance(t, (str,unicode)): t = self.by_ident.get(cast_bytes(t), t) _targets.append(t) targets = _targets bad_targets = [ t for t in targets if t not in self.ids ] if bad_targets: raise IndexError("No Such Engine: %r" % bad_targets) if not targets: raise IndexError("No Engines Registered") return targets
def dispatch_notification(self, msg): """dispatch register/unregister events.""" try: idents,msg = self.session.feed_identities(msg) except ValueError: self.log.warn("task::Invalid Message: %r",msg) return try: msg = self.session.unserialize(msg) except ValueError: self.log.warn("task::Unauthorized message from: %r"%idents) return msg_type = msg['header']['msg_type'] handler = self._notification_handlers.get(msg_type, None) if handler is None: self.log.error("Unhandled message type: %r"%msg_type) else: try: handler(cast_bytes(msg['content']['uuid'])) except Exception: self.log.error("task::Invalid notification msg: %r", msg, exc_info=True)
def pandoc(source, fmt, to, extra_args=None, encoding='utf-8'): """Convert an input string in format `from` to format `to` via pandoc. Parameters ---------- source : string Input string, assumed to be valid format `from`. fmt : string The name of the input format (markdown, etc.) to : string The name of the output format (html, etc.) Returns ------- out : unicode Output as returned by pandoc. Raises ------ PandocMissing If pandoc is not installed. Any error messages generated by pandoc are printed to stderr. """ cmd = ['pandoc', '-f', fmt, '-t', to] if extra_args: cmd.extend(extra_args) # this will raise an exception that will pop us out of here check_pandoc_version() # we can safely continue p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE) out, _ = p.communicate(cast_bytes(source, encoding)) out = TextIOWrapper(BytesIO(out), encoding, 'replace').read() return out.rstrip('\n')
def save_task_destination(self, idents, msg): try: msg = self.session.unserialize(msg, content=True) except Exception: self.log.error("task::invalid task tracking message", exc_info=True) return content = msg['content'] # print (content) msg_id = content['msg_id'] engine_uuid = content['engine_id'] eid = self.by_ident[cast_bytes(engine_uuid)] self.log.info("task::task %r arrived on %r", msg_id, eid) if msg_id in self.unassigned: self.unassigned.remove(msg_id) # else: # self.log.debug("task::task %r not listed as MIA?!"%(msg_id)) self.tasks[eid].append(msg_id) # self.pending[msg_id][1].update(received=datetime.now(),engine=(eid,engine_uuid)) try: self.db.update_record(msg_id, dict(engine_uuid=engine_uuid)) except Exception: self.log.error("DB Error saving task destination %r", msg_id, exc_info=True)
def _ident_changed(self, name, old, new): self.bident = cast_bytes(new)
def run(self, parameter_s='', runner=None, file_finder=get_py_filename): """Run the named file inside IPython as a program. Usage:: %run [-n -i -e -G] [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )] ( -m mod | file ) [args] Parameters after the filename are passed as command-line arguments to the program (put in sys.argv). Then, control returns to IPython's prompt. This is similar to running at a system prompt ``python file args``, but with the advantage of giving you IPython's tracebacks, and of loading all variables into your interactive namespace for further use (unless -p is used, see below). The file is executed in a namespace initially consisting only of ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus sees its environment as if it were being run as a stand-alone program (except for sharing global objects such as previously imported modules). But after execution, the IPython interactive namespace gets updated with all variables defined in the program (except for __name__ and sys.argv). This allows for very convenient loading of code for interactive work, while giving each program a 'clean sheet' to run in. Arguments are expanded using shell-like glob match. Patterns '*', '?', '[seq]' and '[!seq]' can be used. Additionally, tilde '~' will be expanded into user's home directory. Unlike real shells, quotation does not suppress expansions. Use *two* back slashes (e.g. ``\\\\*``) to suppress expansions. To completely disable these expansions, you can use -G flag. Options: -n __name__ is NOT set to '__main__', but to the running file's name without extension (as python does under import). This allows running scripts and reloading the definitions in them without calling code protected by an ``if __name__ == "__main__"`` clause. -i run the file in IPython's namespace instead of an empty one. This is useful if you are experimenting with code written in a text editor which depends on variables defined interactively. -e ignore sys.exit() calls or SystemExit exceptions in the script being run. This is particularly useful if IPython is being used to run unittests, which always exit with a sys.exit() call. In such cases you are interested in the output of the test results, not in seeing a traceback of the unittest module. -t print timing information at the end of the run. IPython will give you an estimated CPU time consumption for your script, which under Unix uses the resource module to avoid the wraparound problems of time.clock(). Under Unix, an estimate of time spent on system tasks is also given (for Windows platforms this is reported as 0.0). If -t is given, an additional ``-N<N>`` option can be given, where <N> must be an integer indicating how many times you want the script to run. The final timing report will include total and per run results. For example (testing the script uniq_stable.py):: In [1]: run -t uniq_stable IPython CPU timings (estimated): User : 0.19597 s. System: 0.0 s. In [2]: run -t -N5 uniq_stable IPython CPU timings (estimated): Total runs performed: 5 Times : Total Per run User : 0.910862 s, 0.1821724 s. System: 0.0 s, 0.0 s. -d run your program under the control of pdb, the Python debugger. This allows you to execute your program step by step, watch variables, etc. Internally, what IPython does is similar to calling:: pdb.run('execfile("YOURFILENAME")') with a breakpoint set on line 1 of your file. You can change the line number for this automatic breakpoint to be <N> by using the -bN option (where N must be an integer). For example:: %run -d -b40 myscript will set the first breakpoint at line 40 in myscript.py. Note that the first breakpoint must be set on a line which actually does something (not a comment or docstring) for it to stop execution. Or you can specify a breakpoint in a different file:: %run -d -b myotherfile.py:20 myscript When the pdb debugger starts, you will see a (Pdb) prompt. You must first enter 'c' (without quotes) to start execution up to the first breakpoint. Entering 'help' gives information about the use of the debugger. You can easily see pdb's full documentation with "import pdb;pdb.help()" at a prompt. -p run program under the control of the Python profiler module (which prints a detailed report of execution times, function calls, etc). You can pass other options after -p which affect the behavior of the profiler itself. See the docs for %prun for details. In this mode, the program's variables do NOT propagate back to the IPython interactive namespace (because they remain in the namespace where the profiler executes them). Internally this triggers a call to %prun, see its documentation for details on the options available specifically for profiling. There is one special usage for which the text above doesn't apply: if the filename ends with .ipy, the file is run as ipython script, just as if the commands were written on IPython prompt. -m specify module name to load instead of script path. Similar to the -m option for the python interpreter. Use this option last if you want to combine with other %run options. Unlike the python interpreter only source modules are allowed no .pyc or .pyo files. For example:: %run -m example will run the example module. -G disable shell-like glob expansion of arguments. """ # get arguments and set sys.argv for program to be run. opts, arg_lst = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:em:G', mode='list', list_all=1) if "m" in opts: modulename = opts["m"][0] modpath = find_mod(modulename) if modpath is None: warn('%r is not a valid modulename on sys.path' % modulename) return arg_lst = [modpath] + arg_lst try: filename = file_finder(arg_lst[0]) except IndexError: warn('you must provide at least a filename.') print '\n%run:\n', oinspect.getdoc(self.run) return except IOError as e: try: msg = str(e) except UnicodeError: msg = e.message error(msg) return if filename.lower().endswith('.ipy'): with preserve_keys(self.shell.user_ns, '__file__'): self.shell.user_ns['__file__'] = filename self.shell.safe_execfile_ipy(filename) return # Control the response to exit() calls made by the script being run exit_ignore = 'e' in opts # Make sure that the running script gets a proper sys.argv as if it # were run from a system shell. save_argv = sys.argv # save it for later restoring if 'G' in opts: args = arg_lst[1:] else: # tilde and glob expansion args = shellglob(map(os.path.expanduser, arg_lst[1:])) sys.argv = [filename] + args # put in the proper filename # protect sys.argv from potential unicode strings on Python 2: if not py3compat.PY3: sys.argv = [py3compat.cast_bytes(a) for a in sys.argv] if 'i' in opts: # Run in user's interactive namespace prog_ns = self.shell.user_ns __name__save = self.shell.user_ns['__name__'] prog_ns['__name__'] = '__main__' main_mod = self.shell.user_module # Since '%run foo' emulates 'python foo.py' at the cmd line, we must # set the __file__ global in the script's namespace # TK: Is this necessary in interactive mode? prog_ns['__file__'] = filename else: # Run in a fresh, empty namespace if 'n' in opts: name = os.path.splitext(os.path.basename(filename))[0] else: name = '__main__' # The shell MUST hold a reference to prog_ns so after %run # exits, the python deletion mechanism doesn't zero it out # (leaving dangling references). See interactiveshell for details main_mod = self.shell.new_main_mod(filename, name) prog_ns = main_mod.__dict__ # pickle fix. See interactiveshell for an explanation. But we need to # make sure that, if we overwrite __main__, we replace it at the end main_mod_name = prog_ns['__name__'] if main_mod_name == '__main__': restore_main = sys.modules['__main__'] else: restore_main = False # This needs to be undone at the end to prevent holding references to # every single object ever created. sys.modules[main_mod_name] = main_mod if 'p' in opts or 'd' in opts: if 'm' in opts: code = 'run_module(modulename, prog_ns)' code_ns = { 'run_module': self.shell.safe_run_module, 'prog_ns': prog_ns, 'modulename': modulename, } else: code = 'execfile(filename, prog_ns)' code_ns = { 'execfile': self.shell.safe_execfile, 'prog_ns': prog_ns, 'filename': get_py_filename(filename), } try: stats = None with self.shell.readline_no_record: if 'p' in opts: stats = self._run_with_profiler(code, opts, code_ns) else: if 'd' in opts: bp_file, bp_line = parse_breakpoint( opts.get('b', ['1'])[0], filename) self._run_with_debugger(code, code_ns, filename, bp_line, bp_file) else: if 'm' in opts: def run(): self.shell.safe_run_module(modulename, prog_ns) else: if runner is None: runner = self.default_runner if runner is None: runner = self.shell.safe_execfile def run(): runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore) if 't' in opts: # timed execution try: nruns = int(opts['N'][0]) if nruns < 1: error('Number of runs must be >=1') return except (KeyError): nruns = 1 self._run_with_timing(run, nruns) else: # regular execution run() if 'i' in opts: self.shell.user_ns['__name__'] = __name__save else: # update IPython interactive namespace # Some forms of read errors on the file may mean the # __name__ key was never set; using pop we don't have to # worry about a possible KeyError. prog_ns.pop('__name__', None) with preserve_keys(self.shell.user_ns, '__file__'): self.shell.user_ns.update(prog_ns) finally: # It's a bit of a mystery why, but __builtins__ can change from # being a module to becoming a dict missing some key data after # %run. As best I can see, this is NOT something IPython is doing # at all, and similar problems have been reported before: # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html # Since this seems to be done by the interpreter itself, the best # we can do is to at least restore __builtins__ for the user on # exit. self.shell.user_ns['__builtins__'] = builtin_mod # Ensure key global structures are restored sys.argv = save_argv if restore_main: sys.modules['__main__'] = restore_main else: # Remove from sys.modules the reference to main_mod we'd # added. Otherwise it will trap references to objects # contained therein. del sys.modules[main_mod_name] return stats
def complete_registration(self, msg, connect, maybe_tunnel): # print msg self._abort_dc.stop() ctx = self.context loop = self.loop identity = self.bident idents, msg = self.session.feed_identities(msg) msg = Message(self.session.unserialize(msg)) if msg.content.status == 'ok': self.id = int(msg.content.id) # launch heartbeat hb_addrs = msg.content.heartbeat # possibly forward hb ports with tunnels hb_addrs = [maybe_tunnel(addr) for addr in hb_addrs] heart = Heart(*map(str, hb_addrs), heart_id=identity) heart.start() # create Shell Streams (MUX, Task, etc.): queue_addr = msg.content.mux shell_addrs = [str(queue_addr)] task_addr = msg.content.task if task_addr: shell_addrs.append(str(task_addr)) # Uncomment this to go back to two-socket model # shell_streams = [] # for addr in shell_addrs: # stream = zmqstream.ZMQStream(ctx.socket(zmq.ROUTER), loop) # stream.setsockopt(zmq.IDENTITY, identity) # stream.connect(disambiguate_url(addr, self.location)) # shell_streams.append(stream) # Now use only one shell stream for mux and tasks stream = zmqstream.ZMQStream(ctx.socket(zmq.ROUTER), loop) stream.setsockopt(zmq.IDENTITY, identity) shell_streams = [stream] for addr in shell_addrs: connect(stream, addr) # end single stream-socket # control stream: control_addr = str(msg.content.control) control_stream = zmqstream.ZMQStream(ctx.socket(zmq.ROUTER), loop) control_stream.setsockopt(zmq.IDENTITY, identity) connect(control_stream, control_addr) # create iopub stream: iopub_addr = msg.content.iopub iopub_socket = ctx.socket(zmq.PUB) iopub_socket.setsockopt(zmq.IDENTITY, identity) connect(iopub_socket, iopub_addr) # disable history: self.config.HistoryManager.hist_file = ':memory:' # Redirect input streams and set a display hook. if self.out_stream_factory: sys.stdout = self.out_stream_factory(self.session, iopub_socket, u'stdout') sys.stdout.topic = cast_bytes('engine.%i.stdout' % self.id) sys.stderr = self.out_stream_factory(self.session, iopub_socket, u'stderr') sys.stderr.topic = cast_bytes('engine.%i.stderr' % self.id) if self.display_hook_factory: sys.displayhook = self.display_hook_factory( self.session, iopub_socket) sys.displayhook.topic = cast_bytes('engine.%i.pyout' % self.id) self.kernel = Kernel(config=self.config, int_id=self.id, ident=self.ident, session=self.session, control_stream=control_stream, shell_streams=shell_streams, iopub_socket=iopub_socket, loop=loop, user_ns=self.user_ns, log=self.log) self.kernel.shell.display_pub.topic = cast_bytes( 'engine.%i.displaypub' % self.id) # FIXME: This is a hack until IPKernelApp and IPEngineApp can be fully merged app = IPKernelApp(config=self.config, shell=self.kernel.shell, kernel=self.kernel, log=self.log) app.init_profile_dir() app.init_code() self.kernel.start() else: self.log.fatal("Registration Failed: %s" % msg) raise Exception("Registration Failed: %s" % msg) self.log.info("Completed registration with id %i" % self.id)
def complete_registration(self, msg, connect, maybe_tunnel): # print msg self._abort_dc.stop() ctx = self.context loop = self.loop identity = self.bident idents, msg = self.session.feed_identities(msg) msg = self.session.unserialize(msg) content = msg['content'] info = self.connection_info def url(key): """get zmq url for given channel""" return str(info["interface"] + ":%i" % info[key]) if content['status'] == 'ok': self.id = int(content['id']) # launch heartbeat # possibly forward hb ports with tunnels hb_ping = maybe_tunnel(url('hb_ping')) hb_pong = maybe_tunnel(url('hb_pong')) heart = Heart(hb_ping, hb_pong, heart_id=identity) heart.start() # create Shell Connections (MUX, Task, etc.): shell_addrs = url('mux'), url('task') # Use only one shell stream for mux and tasks stream = zmqstream.ZMQStream(ctx.socket(zmq.ROUTER), loop) stream.setsockopt(zmq.IDENTITY, identity) shell_streams = [stream] for addr in shell_addrs: connect(stream, addr) # control stream: control_addr = url('control') control_stream = zmqstream.ZMQStream(ctx.socket(zmq.ROUTER), loop) control_stream.setsockopt(zmq.IDENTITY, identity) connect(control_stream, control_addr) # create iopub stream: iopub_addr = url('iopub') iopub_socket = ctx.socket(zmq.PUB) iopub_socket.setsockopt(zmq.IDENTITY, identity) connect(iopub_socket, iopub_addr) # disable history: self.config.HistoryManager.hist_file = ':memory:' # Redirect input streams and set a display hook. if self.out_stream_factory: sys.stdout = self.out_stream_factory(self.session, iopub_socket, u'stdout') sys.stdout.topic = cast_bytes('engine.%i.stdout' % self.id) sys.stderr = self.out_stream_factory(self.session, iopub_socket, u'stderr') sys.stderr.topic = cast_bytes('engine.%i.stderr' % self.id) if self.display_hook_factory: sys.displayhook = self.display_hook_factory( self.session, iopub_socket) sys.displayhook.topic = cast_bytes('engine.%i.pyout' % self.id) self.kernel = Kernel(config=self.config, int_id=self.id, ident=self.ident, session=self.session, control_stream=control_stream, shell_streams=shell_streams, iopub_socket=iopub_socket, loop=loop, user_ns=self.user_ns, log=self.log) self.kernel.shell.display_pub.topic = cast_bytes( 'engine.%i.displaypub' % self.id) # FIXME: This is a hack until IPKernelApp and IPEngineApp can be fully merged app = IPKernelApp(config=self.config, shell=self.kernel.shell, kernel=self.kernel, log=self.log) app.init_profile_dir() app.init_code() self.kernel.start() else: self.log.fatal("Registration Failed: %s" % msg) raise Exception("Registration Failed: %s" % msg) self.log.info("Completed registration with id %i" % self.id)
def complete_registration(self, msg, connect, maybe_tunnel): # print msg self.loop.remove_timeout(self._abort_timeout) ctx = self.context loop = self.loop identity = self.bident idents,msg = self.session.feed_identities(msg) msg = self.session.deserialize(msg) content = msg['content'] info = self.connection_info def url(key): """get zmq url for given channel""" return str(info["interface"] + ":%i" % info[key]) if content['status'] == 'ok': self.id = int(content['id']) # launch heartbeat # possibly forward hb ports with tunnels hb_ping = maybe_tunnel(url('hb_ping')) hb_pong = maybe_tunnel(url('hb_pong')) hb_monitor = None if self.max_heartbeat_misses > 0: # Add a monitor socket which will record the last time a ping was seen mon = self.context.socket(zmq.SUB) mport = mon.bind_to_random_port('tcp://%s' % localhost()) mon.setsockopt(zmq.SUBSCRIBE, b"") self._hb_listener = zmqstream.ZMQStream(mon, self.loop) self._hb_listener.on_recv(self._report_ping) hb_monitor = "tcp://%s:%i" % (localhost(), mport) heart = Heart(hb_ping, hb_pong, hb_monitor , heart_id=identity) heart.start() # create Shell Connections (MUX, Task, etc.): shell_addrs = url('mux'), url('task') # Use only one shell stream for mux and tasks stream = zmqstream.ZMQStream(ctx.socket(zmq.ROUTER), loop) stream.setsockopt(zmq.IDENTITY, identity) shell_streams = [stream] for addr in shell_addrs: connect(stream, addr) # control stream: control_addr = url('control') control_stream = zmqstream.ZMQStream(ctx.socket(zmq.ROUTER), loop) control_stream.setsockopt(zmq.IDENTITY, identity) connect(control_stream, control_addr) # create iopub stream: iopub_addr = url('iopub') iopub_socket = ctx.socket(zmq.PUB) iopub_socket.setsockopt(zmq.IDENTITY, identity) connect(iopub_socket, iopub_addr) # disable history: self.config.HistoryManager.hist_file = ':memory:' # Redirect input streams and set a display hook. if self.out_stream_factory: sys.stdout = self.out_stream_factory(self.session, iopub_socket, u'stdout') sys.stdout.topic = cast_bytes('engine.%i.stdout' % self.id) sys.stderr = self.out_stream_factory(self.session, iopub_socket, u'stderr') sys.stderr.topic = cast_bytes('engine.%i.stderr' % self.id) if self.display_hook_factory: sys.displayhook = self.display_hook_factory(self.session, iopub_socket) sys.displayhook.topic = cast_bytes('engine.%i.execute_result' % self.id) self.kernel = Kernel(parent=self, int_id=self.id, ident=self.ident, session=self.session, control_stream=control_stream, shell_streams=shell_streams, iopub_socket=iopub_socket, loop=loop, user_ns=self.user_ns, log=self.log) self.kernel.shell.display_pub.topic = cast_bytes('engine.%i.displaypub' % self.id) # periodically check the heartbeat pings of the controller # Should be started here and not in "start()" so that the right period can be taken # from the hubs HeartBeatMonitor.period if self.max_heartbeat_misses > 0: # Use a slightly bigger check period than the hub signal period to not warn unnecessary self.hb_check_period = int(content['hb_period'])+10 self.log.info("Starting to monitor the heartbeat signal from the hub every %i ms." , self.hb_check_period) self._hb_reporter = ioloop.PeriodicCallback(self._hb_monitor, self.hb_check_period, self.loop) self._hb_reporter.start() else: self.log.info("Monitoring of the heartbeat signal from the hub is not enabled.") # FIXME: This is a hack until IPKernelApp and IPEngineApp can be fully merged app = IPKernelApp(parent=self, shell=self.kernel.shell, kernel=self.kernel, log=self.log) app.init_profile_dir() app.init_code() self.kernel.start() else: self.log.fatal("Registration Failed: %s"%msg) raise Exception("Registration Failed: %s"%msg) self.log.info("Completed registration with id %i"%self.id)
def run(self, parameter_s='', runner=None, file_finder=get_py_filename): """Run the named file inside IPython as a program. Usage:\\ %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options] -G] file [args] Parameters after the filename are passed as command-line arguments to the program (put in sys.argv). Then, control returns to IPython's prompt. This is similar to running at a system prompt:\\ $ python file args\\ but with the advantage of giving you IPython's tracebacks, and of loading all variables into your interactive namespace for further use (unless -p is used, see below). The file is executed in a namespace initially consisting only of __name__=='__main__' and sys.argv constructed as indicated. It thus sees its environment as if it were being run as a stand-alone program (except for sharing global objects such as previously imported modules). But after execution, the IPython interactive namespace gets updated with all variables defined in the program (except for __name__ and sys.argv). This allows for very convenient loading of code for interactive work, while giving each program a 'clean sheet' to run in. Arguments are expanded using shell-like glob match. Patterns '*', '?', '[seq]' and '[!seq]' can be used. Additionally, tilde '~' will be expanded into user's home directory. Unlike real shells, quotation does not suppress expansions. Use *two* back slashes (e.g., '\\\\*') to suppress expansions. To completely disable these expansions, you can use -G flag. Options: -n: __name__ is NOT set to '__main__', but to the running file's name without extension (as python does under import). This allows running scripts and reloading the definitions in them without calling code protected by an ' if __name__ == "__main__" ' clause. -i: run the file in IPython's namespace instead of an empty one. This is useful if you are experimenting with code written in a text editor which depends on variables defined interactively. -e: ignore sys.exit() calls or SystemExit exceptions in the script being run. This is particularly useful if IPython is being used to run unittests, which always exit with a sys.exit() call. In such cases you are interested in the output of the test results, not in seeing a traceback of the unittest module. -t: print timing information at the end of the run. IPython will give you an estimated CPU time consumption for your script, which under Unix uses the resource module to avoid the wraparound problems of time.clock(). Under Unix, an estimate of time spent on system tasks is also given (for Windows platforms this is reported as 0.0). If -t is given, an additional -N<N> option can be given, where <N> must be an integer indicating how many times you want the script to run. The final timing report will include total and per run results. For example (testing the script uniq_stable.py):: In [1]: run -t uniq_stable IPython CPU timings (estimated):\\ User : 0.19597 s.\\ System: 0.0 s.\\ In [2]: run -t -N5 uniq_stable IPython CPU timings (estimated):\\ Total runs performed: 5\\ Times : Total Per run\\ User : 0.910862 s, 0.1821724 s.\\ System: 0.0 s, 0.0 s. -d: run your program under the control of pdb, the Python debugger. This allows you to execute your program step by step, watch variables, etc. Internally, what IPython does is similar to calling: pdb.run('execfile("YOURFILENAME")') with a breakpoint set on line 1 of your file. You can change the line number for this automatic breakpoint to be <N> by using the -bN option (where N must be an integer). For example:: %run -d -b40 myscript will set the first breakpoint at line 40 in myscript.py. Note that the first breakpoint must be set on a line which actually does something (not a comment or docstring) for it to stop execution. Or you can specify a breakpoint in a different file:: %run -d -b myotherfile.py:20 myscript When the pdb debugger starts, you will see a (Pdb) prompt. You must first enter 'c' (without quotes) to start execution up to the first breakpoint. Entering 'help' gives information about the use of the debugger. You can easily see pdb's full documentation with "import pdb;pdb.help()" at a prompt. -p: run program under the control of the Python profiler module (which prints a detailed report of execution times, function calls, etc). You can pass other options after -p which affect the behavior of the profiler itself. See the docs for %prun for details. In this mode, the program's variables do NOT propagate back to the IPython interactive namespace (because they remain in the namespace where the profiler executes them). Internally this triggers a call to %prun, see its documentation for details on the options available specifically for profiling. There is one special usage for which the text above doesn't apply: if the filename ends with .ipy, the file is run as ipython script, just as if the commands were written on IPython prompt. -m: specify module name to load instead of script path. Similar to the -m option for the python interpreter. Use this option last if you want to combine with other %run options. Unlike the python interpreter only source modules are allowed no .pyc or .pyo files. For example:: %run -m example will run the example module. -G: disable shell-like glob expansion of arguments. """ # get arguments and set sys.argv for program to be run. opts, arg_lst = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:em:G', mode='list', list_all=1) if "m" in opts: modulename = opts["m"][0] modpath = find_mod(modulename) if modpath is None: warn('%r is not a valid modulename on sys.path'%modulename) return arg_lst = [modpath] + arg_lst try: filename = file_finder(arg_lst[0]) except IndexError: warn('you must provide at least a filename.') print '\n%run:\n', oinspect.getdoc(self.run) return except IOError as e: try: msg = str(e) except UnicodeError: msg = e.message error(msg) return if filename.lower().endswith('.ipy'): with preserve_keys(self.shell.user_ns, '__file__'): self.shell.user_ns['__file__'] = filename self.shell.safe_execfile_ipy(filename) return # Control the response to exit() calls made by the script being run exit_ignore = 'e' in opts # Make sure that the running script gets a proper sys.argv as if it # were run from a system shell. save_argv = sys.argv # save it for later restoring if 'G' in opts: args = arg_lst[1:] else: # tilde and glob expansion args = shellglob(map(os.path.expanduser, arg_lst[1:])) sys.argv = [filename] + args # put in the proper filename # protect sys.argv from potential unicode strings on Python 2: if not py3compat.PY3: sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ] if 'i' in opts: # Run in user's interactive namespace prog_ns = self.shell.user_ns __name__save = self.shell.user_ns['__name__'] prog_ns['__name__'] = '__main__' main_mod = self.shell.new_main_mod(prog_ns) else: # Run in a fresh, empty namespace if 'n' in opts: name = os.path.splitext(os.path.basename(filename))[0] else: name = '__main__' main_mod = self.shell.new_main_mod() prog_ns = main_mod.__dict__ prog_ns['__name__'] = name # Since '%run foo' emulates 'python foo.py' at the cmd line, we must # set the __file__ global in the script's namespace prog_ns['__file__'] = filename # pickle fix. See interactiveshell for an explanation. But we need to # make sure that, if we overwrite __main__, we replace it at the end main_mod_name = prog_ns['__name__'] if main_mod_name == '__main__': restore_main = sys.modules['__main__'] else: restore_main = False # This needs to be undone at the end to prevent holding references to # every single object ever created. sys.modules[main_mod_name] = main_mod try: stats = None with self.shell.readline_no_record: if 'p' in opts: stats = self.prun('', None, False, opts, arg_lst, prog_ns) else: if 'd' in opts: deb = debugger.Pdb(self.shell.colors) # reset Breakpoint state, which is moronically kept # in a class bdb.Breakpoint.next = 1 bdb.Breakpoint.bplist = {} bdb.Breakpoint.bpbynumber = [None] # Set an initial breakpoint to stop execution maxtries = 10 bp_file, bp_line = parse_breakpoint(opts.get('b', [1])[0], filename) checkline = deb.checkline(bp_file, bp_line) if not checkline: for bp in range(bp_line + 1, bp_line + maxtries + 1): if deb.checkline(bp_file, bp): break else: msg = ("\nI failed to find a valid line to set " "a breakpoint\n" "after trying up to line: %s.\n" "Please set a valid breakpoint manually " "with the -b option." % bp) error(msg) return # if we find a good linenumber, set the breakpoint deb.do_break('%s:%s' % (bp_file, bp_line)) # Mimic Pdb._runscript(...) deb._wait_for_mainpyfile = True deb.mainpyfile = deb.canonic(filename) # Start file run print "NOTE: Enter 'c' at the", print "%s prompt to start your script." % deb.prompt ns = {'execfile': py3compat.execfile, 'prog_ns': prog_ns} try: #save filename so it can be used by methods on the deb object deb._exec_filename = filename deb.run('execfile("%s", prog_ns)' % filename, ns) except: etype, value, tb = sys.exc_info() # Skip three frames in the traceback: the %run one, # one inside bdb.py, and the command-line typed by the # user (run by exec in pdb itself). self.shell.InteractiveTB(etype, value, tb, tb_offset=3) else: if runner is None: runner = self.default_runner if runner is None: runner = self.shell.safe_execfile if 't' in opts: # timed execution try: nruns = int(opts['N'][0]) if nruns < 1: error('Number of runs must be >=1') return except (KeyError): nruns = 1 twall0 = time.time() if nruns == 1: t0 = clock2() runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore) t1 = clock2() t_usr = t1[0] - t0[0] t_sys = t1[1] - t0[1] print "\nIPython CPU timings (estimated):" print " User : %10.2f s." % t_usr print " System : %10.2f s." % t_sys else: runs = range(nruns) t0 = clock2() for nr in runs: runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore) t1 = clock2() t_usr = t1[0] - t0[0] t_sys = t1[1] - t0[1] print "\nIPython CPU timings (estimated):" print "Total runs performed:", nruns print " Times : %10.2f %10.2f" % ('Total', 'Per run') print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns) print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns) twall1 = time.time() print "Wall time: %10.2f s." % (twall1 - twall0) else: # regular execution runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore) if 'i' in opts: self.shell.user_ns['__name__'] = __name__save else: # The shell MUST hold a reference to prog_ns so after %run # exits, the python deletion mechanism doesn't zero it out # (leaving dangling references). self.shell.cache_main_mod(prog_ns, filename) # update IPython interactive namespace # Some forms of read errors on the file may mean the # __name__ key was never set; using pop we don't have to # worry about a possible KeyError. prog_ns.pop('__name__', None) with preserve_keys(self.shell.user_ns, '__file__'): self.shell.user_ns.update(prog_ns) finally: # It's a bit of a mystery why, but __builtins__ can change from # being a module to becoming a dict missing some key data after # %run. As best I can see, this is NOT something IPython is doing # at all, and similar problems have been reported before: # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html # Since this seems to be done by the interpreter itself, the best # we can do is to at least restore __builtins__ for the user on # exit. self.shell.user_ns['__builtins__'] = builtin_mod # Ensure key global structures are restored sys.argv = save_argv if restore_main: sys.modules['__main__'] = restore_main else: # Remove from sys.modules the reference to main_mod we'd # added. Otherwise it will trap references to objects # contained therein. del sys.modules[main_mod_name] return stats
def preprocess_cell(self, cell, resources, cell_index): """ Apply a transformation on each cell, Parameters ---------- cell : NotebookNode cell Notebook cell being processed resources : dictionary Additional resources used in the conversion process. Allows preprocessors to pass variables into the Jinja engine. cell_index : int Index of the cell being processed (see base.py) """ #Get the unique key from the resource dict if it exists. If it does not #exist, use 'output' as the default. Also, get files directory if it #has been specified unique_key = resources.get('unique_key', 'output') output_files_dir = resources.get('output_files_dir', None) #Make sure outputs key exists if not isinstance(resources['outputs'], dict): resources['outputs'] = {} #Loop through all of the outputs in the cell for index, out in enumerate(cell.get('outputs', [])): #Get the output in data formats that the template is interested in. for out_type in self.display_data_priority: if out.hasattr(out_type): data = out[out_type] #Binary files are base64-encoded, SVG is already XML if out_type in ('png', 'jpg', 'jpeg', 'pdf'): # data is b64-encoded as text (str, unicode) # decodestring only accepts bytes data = py3compat.cast_bytes(data) data = base64.decodestring(data) elif sys.platform == 'win32': data = data.replace('\n', '\r\n').encode("UTF-8") else: data = data.encode("UTF-8") #Build an output name filename = self.output_filename_template.format( unique_key=unique_key, cell_index=cell_index, index=index, extension=out_type) #On the cell, make the figure available via # cell.outputs[i].svg_filename ... etc (svg in example) # Where # cell.outputs[i].svg contains the data if output_files_dir is not None: filename = os.path.join(output_files_dir, filename) out[out_type + '_filename'] = filename #In the resources, make the figure available via # resources['outputs']['filename'] = data resources['outputs'][filename] = data return cell, resources