def profile(self, parameter_s=''): """Print your currently active IPython profile.""" from IPython.core.application import BaseIPythonApplication if BaseIPythonApplication.initialized(): print(BaseIPythonApplication.instance().profile) else: error("profile is an application-level value, but you don't appear to be in an IPython application")
def _assert_ipython_dir(): # Fix OOIION-1124: # When multiple containers are started in parallel, all start an embedded IPython shell/manhole. # There might be a race condition between the IPython creating the default $HOME/.python dir # leading to an error. Prevent this by... homedir = os.path.expanduser('~') homedir = os.path.realpath(homedir) home_ipdir = os.path.join(homedir, ".ipython") ipdir = os.path.normpath(os.path.expanduser(home_ipdir)) if not os.path.exists(ipdir): log.warn("%s not found. Preventing potential race condition", ipdir) for tries in range(3): try: import gevent import random gevent.sleep(random.random() * 0.1) from IPython.core.application import BaseIPythonApplication ba = BaseIPythonApplication() ba.initialize() if os.path.exists(ipdir): log.debug("Success initializing IPython") break except Exception as ex: log.debug("Failed IPython initialize attempt (try #%s): %s", tries, str(ex)) # At this point there should be if not os.path.exists(ipdir): log.error("%s not found after several tries", ipdir)
def __init__(self, **kwargs): super(SQLiteDB, self).__init__(**kwargs) if sqlite3 is None: raise ImportError("SQLiteDB requires sqlite3") if not self.table: # use session, and prefix _, since starting with # is illegal self.table = '_' + self.session.replace('-', '_') if not self.location: # get current profile from IPython.core.application import BaseIPythonApplication if BaseIPythonApplication.initialized(): app = BaseIPythonApplication.instance() if app.profile_dir is not None: self.location = app.profile_dir.location else: self.location = u'.' else: self.location = u'.' self._init_db() # register db commit as 2s periodic callback # to prevent clogging pipes # assumes we are being run in a zmq ioloop app loop = ioloop.IOLoop.instance() pc = ioloop.PeriodicCallback(self._db.commit, 2000, loop) pc.start()
def __init__(self, **kwargs): super(SQLiteDB, self).__init__(**kwargs) if sqlite3 is None: raise ImportError("SQLiteDB requires sqlite3") if not self.table: # use session, and prefix _, since starting with # is illegal self.table = '_'+self.session.replace('-','_') if not self.location: # get current profile from IPython.core.application import BaseIPythonApplication if BaseIPythonApplication.initialized(): app = BaseIPythonApplication.instance() if app.profile_dir is not None: self.location = app.profile_dir.location else: self.location = u'.' else: self.location = u'.' self._init_db() # register db commit as 2s periodic callback # to prevent clogging pipes # assumes we are being run in a zmq ioloop app loop = ioloop.IOLoop.instance() pc = ioloop.PeriodicCallback(self._db.commit, 2000, loop) pc.start()
def _profile_dir_default(self): from IPython.core.application import BaseIPythonApplication app = None try: if BaseIPythonApplication.initialized(): app = BaseIPythonApplication.instance() except MultipleInstanceError: pass if app is None: # create an app, without the global instance app = BaseIPythonApplication() app.initialize(argv=[]) return app.profile_dir
def profile(self, parameter_s=''): """Print your currently active IPython profile. See Also -------- prun : run code using the Python profiler (:meth:`~IPython.core.magics.execution.ExecutionMagics.prun`) """ warn("%profile is now deprecated. Please use get_ipython().profile instead.") from IPython.core.application import BaseIPythonApplication if BaseIPythonApplication.initialized(): print(BaseIPythonApplication.instance().profile) else: error("profile is an application-level value, but you don't appear to be in an IPython application")
def find_connection_file(filename='kernel-*.json', profile=None): """find a connection file, and return its absolute path. The current working directory and the profile's security directory will be searched for the file if it is not given by absolute path. If profile is unspecified, then the current running application's profile will be used, or 'default', if not run from IPython. If the argument does not match an existing file, it will be interpreted as a fileglob, and the matching file in the profile's security dir with the latest access time will be used. Parameters ---------- filename : str The connection file or fileglob to search for. profile : str [optional] The name of the profile to use when searching for the connection file, if different from the current IPython session or 'default'. Returns ------- str : The absolute path of the connection file. """ from IPython.core.application import BaseIPythonApplication as IPApp try: # quick check for absolute path, before going through logic return filefind(filename) except IOError: pass if profile is None: # profile unspecified, check if running from an IPython app if IPApp.initialized(): app = IPApp.instance() profile_dir = app.profile_dir else: # not running in IPython, use default profile profile_dir = ProfileDir.find_profile_dir_by_name( get_ipython_dir(), 'default') else: # find profiledir by profile name: profile_dir = ProfileDir.find_profile_dir_by_name( get_ipython_dir(), profile) security_dir = profile_dir.security_dir return jupyter_client.find_connection_file(filename, path=['.', security_dir])
def magic_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 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 profile(self, parameter_s=''): """DEPRECATED since IPython 2.0. Raise `UsageError`. To profile code use the :magic:`prun` magic. See Also -------- prun : run code using the Python profiler (:magic:`prun`) """ warn("%profile is now deprecated. Please use get_ipython().profile instead.") from IPython.core.application import BaseIPythonApplication if BaseIPythonApplication.initialized(): print(BaseIPythonApplication.instance().profile) else: error("profile is an application-level value, but you don't appear to be in an IPython application")
def find_connection_file(filename='kernel-*.json', profile=None): """find a connection file, and return its absolute path. The current working directory and the profile's security directory will be searched for the file if it is not given by absolute path. If profile is unspecified, then the current running application's profile will be used, or 'default', if not run from IPython. If the argument does not match an existing file, it will be interpreted as a fileglob, and the matching file in the profile's security dir with the latest access time will be used. Parameters ---------- filename : str The connection file or fileglob to search for. profile : str [optional] The name of the profile to use when searching for the connection file, if different from the current IPython session or 'default'. Returns ------- str : The absolute path of the connection file. """ from IPython.core.application import BaseIPythonApplication as IPApp try: # quick check for absolute path, before going through logic return filefind(filename) except IOError: pass if profile is None: # profile unspecified, check if running from an IPython app if IPApp.initialized(): app = IPApp.instance() profile_dir = app.profile_dir else: # not running in IPython, use default profile profile_dir = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), 'default') else: # find profiledir by profile name: profile_dir = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile) security_dir = profile_dir.security_dir return jupyter_client.find_connection_file(filename, path=['.', security_dir])
def find_connection_file(filename='kernel-*.json', profile=None): """DEPRECATED: find a connection file, and return its absolute path. THIS FUNCTION IS DEPRECATED. Use juptyer_client.find_connection_file instead. Parameters ---------- filename : str The connection file or fileglob to search for. profile : str [optional] The name of the profile to use when searching for the connection file, if different from the current IPython session or 'default'. Returns ------- str : The absolute path of the connection file. """ import warnings warnings.warn( """ipykernel.find_connection_file is deprecated, use jupyter_client.find_connection_file""", DeprecationWarning, stacklevel=2) from IPython.core.application import BaseIPythonApplication as IPApp try: # quick check for absolute path, before going through logic return filefind(filename) except IOError: pass if profile is None: # profile unspecified, check if running from an IPython app if IPApp.initialized(): app = IPApp.instance() profile_dir = app.profile_dir else: # not running in IPython, use default profile profile_dir = ProfileDir.find_profile_dir_by_name( get_ipython_dir(), 'default') else: # find profiledir by profile name: profile_dir = ProfileDir.find_profile_dir_by_name( get_ipython_dir(), profile) security_dir = profile_dir.security_dir return jupyter_client.find_connection_file(filename, path=['.', security_dir])
def find_connection_file(filename='kernel-*.json', profile=None): """DEPRECATED: find a connection file, and return its absolute path. THIS FUNCION IS DEPRECATED. Use juptyer_client.find_connection_file instead. Parameters ---------- filename : str The connection file or fileglob to search for. profile : str [optional] The name of the profile to use when searching for the connection file, if different from the current IPython session or 'default'. Returns ------- str : The absolute path of the connection file. """ import warnings warnings.warn("""ipykernel.find_connection_file is deprecated, use jupyter_client.find_connection_file""", DeprecationWarning, stacklevel=2) from IPython.core.application import BaseIPythonApplication as IPApp try: # quick check for absolute path, before going through logic return filefind(filename) except IOError: pass if profile is None: # profile unspecified, check if running from an IPython app if IPApp.initialized(): app = IPApp.instance() profile_dir = app.profile_dir else: # not running in IPython, use default profile profile_dir = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), 'default') else: # find profiledir by profile name: profile_dir = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile) security_dir = profile_dir.security_dir return jupyter_client.find_connection_file(filename, path=['.', security_dir])
def test_unicode_cwd(): """Check that IPython starts with non-ascii characters in the path.""" wd = tempfile.mkdtemp(suffix=u"€") old_wd = py3compat.getcwd() os.chdir(wd) #raise Exception(repr(py3compat.getcwd())) try: app = BaseIPythonApplication() # The lines below are copied from Application.initialize() app.init_profile_dir() app.init_config_files() app.load_config_file(suppress_errors=False) finally: os.chdir(old_wd)
def test_unicode_cwd(): """Check that IPython starts with non-ascii characters in the path.""" wd = tempfile.mkdtemp(suffix=u"€") old_wd = os.getcwdu() os.chdir(wd) #raise Exception(repr(os.getcwdu())) try: app = BaseIPythonApplication() # The lines below are copied from Application.initialize() app.init_profile_dir() app.init_config_files() app.load_config_file(suppress_errors=False) finally: os.chdir(old_wd)
def test_unicode_ipdir(): """Check that IPython starts with non-ascii characters in the IP dir.""" ipdir = tempfile.mkdtemp(suffix=u"€") # Create the config file, so it tries to load it. with open(os.path.join(ipdir, 'ipython_config.py'), "w") as f: pass old_ipdir1 = os.environ.pop("IPYTHONDIR", None) old_ipdir2 = os.environ.pop("IPYTHON_DIR", None) os.environ["IPYTHONDIR"] = py3compat.unicode_to_str(ipdir, "utf-8") try: app = BaseIPythonApplication() # The lines below are copied from Application.initialize() app.init_profile_dir() app.init_config_files() app.load_config_file(suppress_errors=False) finally: if old_ipdir1: os.environ["IPYTHONDIR"] = old_ipdir1 if old_ipdir2: os.environ["IPYTHONDIR"] = old_ipdir2
def find_connection_file(filename, profile=None): """find a connection file, and return its absolute path. The current working directory and the profile's security directory will be searched for the file if it is not given by absolute path. If profile is unspecified, then the current running application's profile will be used, or 'default', if not run from IPython. If the argument does not match an existing file, it will be interpreted as a fileglob, and the matching file in the profile's security dir with the latest access time will be used. Parameters ---------- filename : str The connection file or fileglob to search for. profile : str [optional] The name of the profile to use when searching for the connection file, if different from the current IPython session or 'default'. Returns ------- str : The absolute path of the connection file. """ from IPython.core.application import BaseIPythonApplication as IPApp try: # quick check for absolute path, before going through logic return filefind(filename) except IOError: pass if profile is None: # profile unspecified, check if running from an IPython app if IPApp.initialized(): app = IPApp.instance() profile_dir = app.profile_dir else: # not running in IPython, use default profile profile_dir = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), 'default') else: # find profiledir by profile name: profile_dir = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile) security_dir = profile_dir.security_dir try: # first, try explicit name return filefind(filename, ['.', security_dir]) except IOError: pass # not found by full name if '*' in filename: # given as a glob already pat = filename else: # accept any substring match pat = '*%s*' % filename matches = glob.glob( os.path.join(security_dir, pat) ) if not matches: raise IOError("Could not find %r in %r" % (filename, security_dir)) elif len(matches) == 1: return matches[0] else: # get most recent match, by access time: return sorted(matches, key=lambda f: os.stat(f).st_atime)[-1]
def initialize(self, argv=[]): BaseIPythonApplication.initialize(self, argv=argv) self.init_connection_file()
def find_connection_file(filename, profile=None): """find a connection file, and return its absolute path. The current working directory and the profile's security directory will be searched for the file if it is not given by absolute path. If profile is unspecified, then the current running application's profile will be used, or 'default', if not run from IPython. If the argument does not match an existing file, it will be interpreted as a fileglob, and the matching file in the profile's security dir with the latest access time will be used. Parameters ---------- filename : str The connection file or fileglob to search for. profile : str [optional] The name of the profile to use when searching for the connection file, if different from the current IPython session or 'default'. Returns ------- str : The absolute path of the connection file. """ from IPython.core.application import BaseIPythonApplication as IPApp try: # quick check for absolute path, before going through logic return filefind(filename) except IOError: pass if profile is None: # profile unspecified, check if running from an IPython app if IPApp.initialized(): app = IPApp.instance() profile_dir = app.profile_dir else: # not running in IPython, use default profile profile_dir = ProfileDir.find_profile_dir_by_name( get_ipython_dir(), 'default') else: # find profiledir by profile name: profile_dir = ProfileDir.find_profile_dir_by_name( get_ipython_dir(), profile) security_dir = profile_dir.security_dir try: # first, try explicit name return filefind(filename, ['.', security_dir]) except IOError: pass # not found by full name if '*' in filename: # given as a glob already pat = filename else: # accept any substring match pat = '*%s*' % filename matches = glob.glob(os.path.join(security_dir, pat)) if not matches: raise IOError("Could not find %r in %r" % (filename, security_dir)) elif len(matches) == 1: return matches[0] else: # get most recent match, by access time: return sorted(matches, key=lambda f: os.stat(f).st_atime)[-1]