Example #1
0
 def to_work_dir(self):
     wd = self.work_dir
     if unicode(wd) != getcwdu():
         os.chdir(wd)
         self.log.info("Changing to working dir: %s" % wd)
     # This is the working dir by now.
     sys.path.insert(0, '')
Example #2
0
    def find_profile_dir_by_name(cls, ipython_dir, name=u'default', config=None):
        """Find an existing profile dir by profile name, return its ProfileDir.

        This searches through a sequence of paths for a profile dir.  If it
        is not found, a :class:`ProfileDirError` exception will be raised.

        The search path algorithm is:
        1. ``getcwdu()``
        2. ``ipython_dir``

        Parameters
        ----------
        ipython_dir : unicode or str
            The IPython directory to use.
        name : unicode or str
            The name of the profile.  The name of the profile directory
            will be "profile_<profile>".
        """
        dirname = u'profile_' + name
        paths = [getcwdu(), ipython_dir]
        for p in paths:
            profile_dir = os.path.join(p, dirname)
            if os.path.isdir(profile_dir):
                return cls(location=profile_dir, config=config)
        else:
            raise ProfileDirError('Profile directory not found in paths: %s' % dirname)
Example #3
0
    def __call__(self, etype, evalue, etb):
        """Handle an exception, call for compatible with sys.excepthook"""

        # Report tracebacks shouldn't use color in general (safer for users)
        color_scheme = "NoColor"

        # Use this ONLY for developer debugging (keep commented out for release)
        # color_scheme = 'Linux'   # dbg
        try:
            rptdir = self.app.ipython_dir
        except:
            rptdir = getcwdu()
        if rptdir is None or not os.path.isdir(rptdir):
            rptdir = getcwdu()
        report_name = os.path.join(rptdir, self.crash_report_fname)
        # write the report filename into the instance dict so it can get
        # properly expanded out in the user message template
        self.crash_report_fname = report_name
        self.info["crash_report_fname"] = report_name
        TBhandler = ultratb.VerboseTB(color_scheme=color_scheme, long_header=1, call_pdb=self.call_pdb)
        if self.call_pdb:
            TBhandler(etype, evalue, etb)
            return
        else:
            traceback = TBhandler.text(etype, evalue, etb, context=31)

        # print traceback to screen
        if self.show_crash_traceback:
            print >>sys.stderr, traceback

        # and generate a complete report on disk
        try:
            report = open(report_name, "w")
        except:
            print >>sys.stderr, "Could not create crash report on disk."
            return

        # Inform user on stderr of what happened
        print >>sys.stderr, "\n" + "*" * 70 + "\n"
        print >>sys.stderr, self.message_template.format(**self.info)

        # Construct report on disk
        report.write(self.make_report(traceback))
        report.close()
        raw_input("Hit <Enter> to quit this message (your terminal may close):")
Example #4
0
    def list_profile_dirs(self):
        # Find the search paths
        paths = [getcwdu(), self.ipython_dir]

        self.log.warn('Searching for IPython profiles in paths: %r' % paths)
        for path in paths:
            files = os.listdir(path)
            for f in files:
                full_path = os.path.join(path, f)
                if os.path.isdir(full_path) and f.startswith('profile_'):
                    profile = f.split('_',1)[-1]
                    start_cmd = 'ipython profile=%s' % profile
                    print start_cmd + " ==> " + full_path
Example #5
0
 def reset(self, new_session=True):
     """Clear the session history, releasing all object references, and
     optionally open a new session."""
     self.output_hist.clear()
     # The directory history can't be completely empty
     self.dir_hist[:] = [getcwdu()]
     
     if new_session:
         if self.session_number:
             self.end_session()
         self.input_hist_parsed[:] = [""]
         self.input_hist_raw[:] = [""]
         self.new_session()
Example #6
0
        def _set_term_title(title):
            """Set terminal title using the 'title' command."""
            global ignore_termtitle

            try:
                # Cannot be on network share when issuing system commands
                curr = getcwdu()
                os.chdir("C:")
                ret = os.system("title " + title)
            finally:
                os.chdir(curr)
            if ret:
                # non-zero return code signals error, don't try again
                ignore_termtitle = True
def test_unicode_cwd():
    """Check that IPython starts with non-ascii characters in the path."""
    wd = tempfile.mkdtemp(suffix=u"€")
    
    old_wd = getcwdu()
    os.chdir(wd)
    #raise Exception(repr(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)
Example #8
0
def test_dirops():
    """Test various directory handling operations."""
    # curpath = lambda :os.path.splitdrive(getcwdu())[1].replace('\\','/')
    curpath = getcwdu
    startdir = getcwdu()
    ipdir = _ip.ipython_dir
    try:
        _ip.magic('cd "%s"' % ipdir)
        nt.assert_equal(curpath(), ipdir)
        _ip.magic('cd -')
        nt.assert_equal(curpath(), startdir)
        _ip.magic('pushd "%s"' % ipdir)
        nt.assert_equal(curpath(), ipdir)
        _ip.magic('popd')
        nt.assert_equal(curpath(), startdir)
    finally:
        os.chdir(startdir)
Example #9
0
def test_local_file_completions():
    ip = get_ipython()
    cwd = getcwdu()
    try:
        with TemporaryDirectory() as tmpdir:
            os.chdir(tmpdir)
            prefix = './foo'
            suffixes = map(str, [1,2])
            names = [prefix+s for s in suffixes]
            for n in names:
                open(n, 'w').close()

            # Check simple completion
            c = ip.complete(prefix)[1]
            nt.assert_equal(c, names)

            # Now check with a function call
            cmd = 'a = f("%s' % prefix
            c = ip.complete(prefix, cmd)[1]
            comp = [prefix+s for s in suffixes]
            nt.assert_equal(c, comp)
    finally:
        # prevent failures from making chdir stick
        os.chdir(cwd)
Example #10
0
 def _config_file_paths_default(self):
     return [getcwdu()]
Example #11
0
 def _dir_hist_default(self):
     try:
         return [getcwdu()]
     except OSError:
         return []
Example #12
0
 def getcwd(cls):
     """ Return the current working directory as a path object. """
     return cls(getcwdu())
Example #13
0
 def relpath(self):
     """ Return this path as a relative path,
     based from the current working directory.
     """
     cwd = self.__class__(getcwdu())
     return cwd.relpathto(self)