def is_in_notebook(): try: ipykernel.get_connection_info() # Temporary fix for #84 # TODO: remove blanket Exception catching after fixing #84 except Exception: return False return True
def connect_info(self, arg_s): """Print information for connecting other clients to this kernel It will print the contents of this session's connection file, as well as shortcuts for local clients. In the simplest case, when called from the most recently launched kernel, secondary clients can be connected, simply with: $> jupyter <app> --existing """ try: connection_file = get_connection_file() info = get_connection_info(unpack=False) except Exception as e: warnings.warn("Could not get connection info: %r" % e) return # if it's in the default dir, truncate to basename if jupyter_runtime_dir() == os.path.dirname(connection_file): connection_file = os.path.basename(connection_file) print(info + '\n') print("Paste the above JSON into a file, and connect with:\n" " $> jupyter <app> --existing <file>\n" "or, if you are local, you can connect with just:\n" " $> jupyter <app> --existing {0}\n" "or even just:\n" " $> jupyter <app> --existing\n" "if this is the most recent Jupyter kernel you have started.". format(connection_file))
def initialize(): log_level = _get_kql_magic_log_level() log_file = os.getenv(f"{Constants.MAGIC_CLASS_NAME.upper()}_LOG_FILE") log_file_prefix = os.getenv( f"{Constants.MAGIC_CLASS_NAME.upper()}_LOG_FILE_PREFIX") log_file_mode = os.getenv( f"{Constants.MAGIC_CLASS_NAME.upper()}_LOG_FILE_MODE") if log_level or log_file or log_file_mode or log_file_prefix: connection_info = get_connection_info(unpack=True) # key is unique per ipkernel instance key = connection_info.get("key").decode(encoding="utf-8") log_level = log_level or logging.DEBUG log_file = log_file or ((log_file_prefix or 'Kqlmagic') + '-' + key + '.log') # handler's default mode is 'a' (append) log_file_mode = (log_file_mode or "w").lower()[:1] log_handler = logging.FileHandler(log_file, mode=log_file_mode) else: log_handler = logging.NullHandler() set_logging_options({'level': log_level, 'handler': log_handler}) set_logger(Logger()) if log_file: if log_file_mode == "a": logger().debug( "\n\n----------------------------------------------------------------------" ) now = datetime.datetime.now() logger().debug("start date %s\n", now.isoformat()) logger().debug("logger level %s\n", log_level) logger().debug("logger init done")
def get_nb_kernel(): ''' Returns a string with the kernel key for unique identification of a kernel. ''' from ipykernel import get_connection_info k = get_connection_info() k_dict = json.loads(k) return k_dict['key']
def get_notebook_connection_info(cls): conn_info = None try: try: import ipykernel as kernel except: from IPython.lib import kernel conn_info = kernel.get_connection_info(unpack=False) except: pass return conn_info
def connect_info(self, arg_s): """Print information for connecting other clients to this kernel It will print the contents of this session's connection file, as well as shortcuts for local clients. In the simplest case, when called from the most recently launched kernel, secondary clients can be connected, simply with: $> ipython <app> --existing """ from IPython.core.application import BaseIPythonApplication as BaseIPApp if BaseIPApp.initialized(): app = BaseIPApp.instance() security_dir = app.profile_dir.security_dir profile = app.profile else: profile = 'default' security_dir = '' try: connection_file = get_connection_file() info = get_connection_info(unpack=False) except Exception as e: error("Could not get connection info: %r" % e) return # add profile flag for non-default profile profile_flag = "--profile %s" % profile if profile != 'default' else "" # if it's in the security dir, truncate to basename if security_dir == os.path.dirname(connection_file): connection_file = os.path.basename(connection_file) print (info + '\n') print ("Paste the above JSON into a file, and connect with:\n" " $> ipython <app> --existing <file>\n" "or, if you are local, you can connect with just:\n" " $> ipython <app> --existing {0} {1}\n" "or even just:\n" " $> ipython <app> --existing {1}\n" "if this is the most recent IPython session you have started.".format( connection_file, profile_flag ) )
def _handle_magics(self, magic_code, code): """ Handle cell magics """ _exec_status = False _content = None err_content = None if(magic_code == 'connect_info'): try: connection_file = get_connection_file() _content = get_connection_info(unpack=False) except Exception as e: error("Could not get connection info: %r" % e) return if(magic_code == 'history'): _args = re.search(r'^%(\S+)(?:\s*)(\d*)', code) self._shell.run_raw('history(' + _args.group(2) + ')') _content = self._shell.output[:-1] if(magic_code == 'help'): _args = re.search(r'^%(\S+)(?:\s*)(\S*)', code) _content = self._shell.get_info(_args.group(2)) if(magic_code == 'image'): _args = re.search(r'^%(\S+)(?:\s*)(\S+)', code) if _args is not None: return self._show_image_inline(_args.group(2)) if(magic_code == 'flush'): self._shell.flush() _content = '' if(_content is not None): execute_content = {'execution_count': self.execution_count, 'data': {'text/plain': _content}, 'metadata': {}} self.send_response(self.iopub_socket, 'execute_result', execute_content) _exec_status = True else: err_content = {'execution_count': self.execution_count, 'ename': str('CellMagicError'), 'evalue': str(1), 'traceback': ['Invalid cell magic']} self.send_response(self.iopub_socket, 'error', err_content) return _exec_status, err_content
def _handle_magics(self, magic_code, code): """ Handle cell magics """ _exec_status = False _content = None err_content = None if(magic_code == 'connect_info'): try: connection_file = get_connection_file() _content = get_connection_info(unpack=False) except Exception as e: error("Could not get connection info: %r" % e) return if(magic_code == 'history'): _args = re.search(r'^%(\S+)(?:\s*)(\d*)', code) self._shell.run_raw('history(' + _args.group(2) + ')') _content = self._shell.output[:-1] if(magic_code == 'help'): _args = re.search(r'^%(\S+)(?:\s*)(\S*)', code) _content = self._shell.get_info(_args.group(2)) if(magic_code == 'image'): _args = re.search(r'^%(\S+)(?:\s*)(\S+)', code) if _args is not None: return self._show_image_inline(_args.group(2)) if(magic_code == 'flush'): _content = '' if(_content is not None): execute_content = {'execution_count': self.execution_count, 'data': {'text/plain': _content}, 'metadata': {}} self.send_response(self.iopub_socket, 'execute_result', execute_content) _exec_status = True else: err_content = {'execution_count': self.execution_count, 'ename': str('CellMagicError'), 'evalue': str(1), 'traceback': ['Invalid cell magic']} self.send_response(self.iopub_socket, 'error', err_content) return _exec_status, err_content
def connect_info(self, arg_s): """Print information for connecting other clients to this kernel It will print the contents of this session's connection file, as well as shortcuts for local clients. In the simplest case, when called from the most recently launched kernel, secondary clients can be connected, simply with: $> jupyter <app> --existing """ try: connection_file = get_connection_file() info = get_connection_info(unpack=False) except Exception as e: warnings.warn("Could not get connection info: %r" % e) return # if it's in the default dir, truncate to basename if jupyter_runtime_dir() == os.path.dirname(connection_file): connection_file = os.path.basename(connection_file) print (info + '\n') print ("Paste the above JSON into a file, and connect with:\n" " $> jupyter <app> --existing <file>\n" "or, if you are local, you can connect with just:\n" " $> jupyter <app> --existing {0}\n" "or even just:\n" " $> jupyter <app> --existing\n" "if this is the most recent Jupyter kernel you have started.".format( connection_file ) )
def is_in_notebook(): try: ipykernel.get_connection_info() except RuntimeError: return False return True