Python os.getcwdu() Examples

The following are 30 code examples of os.getcwdu(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module os , or try the search function .
Example #1
Source File: test_fixers.py    From Computable with MIT License 6 votes vote down vote up
def test_basic(self):
        b = """os.getcwdu"""
        a = """os.getcwd"""
        self.check(b, a)

        b = """os.getcwdu()"""
        a = """os.getcwd()"""
        self.check(b, a)

        b = """meth = os.getcwdu"""
        a = """meth = os.getcwd"""
        self.check(b, a)

        b = """os.getcwdu(args)"""
        a = """os.getcwd(args)"""
        self.check(b, a) 
Example #2
Source File: test_fixers.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_basic(self):
        b = """os.getcwdu"""
        a = """os.getcwd"""
        self.check(b, a)

        b = """os.getcwdu()"""
        a = """os.getcwd()"""
        self.check(b, a)

        b = """meth = os.getcwdu"""
        a = """meth = os.getcwd"""
        self.check(b, a)

        b = """os.getcwdu(args)"""
        a = """os.getcwd(args)"""
        self.check(b, a) 
Example #3
Source File: test_fixers.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_basic(self):
        b = """os.getcwdu"""
        a = """os.getcwd"""
        self.check(b, a)

        b = """os.getcwdu()"""
        a = """os.getcwd()"""
        self.check(b, a)

        b = """meth = os.getcwdu"""
        a = """meth = os.getcwd"""
        self.check(b, a)

        b = """os.getcwdu(args)"""
        a = """os.getcwd(args)"""
        self.check(b, a) 
Example #4
Source File: coverage.py    From oscrypto with MIT License 6 votes vote down vote up
def _env_info():
    """
    :return:
        A two-element tuple of unicode strings. The first is the name of the
        environment, the second the root of the repo. The environment name
        will be one of: "ci-travis", "ci-circle", "ci-appveyor",
        "ci-github-actions", "local"
    """

    if os.getenv('CI') == 'true' and os.getenv('TRAVIS') == 'true':
        return ('ci-travis', os.getenv('TRAVIS_BUILD_DIR'))

    if os.getenv('CI') == 'True' and os.getenv('APPVEYOR') == 'True':
        return ('ci-appveyor', os.getenv('APPVEYOR_BUILD_FOLDER'))

    if os.getenv('CI') == 'true' and os.getenv('CIRCLECI') == 'true':
        return ('ci-circle', os.getcwdu() if sys.version_info < (3,) else os.getcwd())

    if os.getenv('GITHUB_ACTIONS') == 'true':
        return ('ci-github-actions', os.getenv('GITHUB_WORKSPACE'))

    return ('local', package_root) 
Example #5
Source File: history.py    From Computable with MIT License 6 votes vote down vote up
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[:] = [os.getcwdu()]
        
        if new_session:
            if self.session_number:
                self.end_session()
            self.input_hist_parsed[:] = [""]
            self.input_hist_raw[:] = [""]
            self.new_session()
    
    # ------------------------------
    # Methods for retrieving history
    # ------------------------------ 
Example #6
Source File: application.py    From Computable with MIT License 6 votes vote down vote up
def __init__(self, **kwargs):
        super(BaseIPythonApplication, self).__init__(**kwargs)
        # ensure current working directory exists
        try:
            directory = os.getcwdu()
        except:
            # raise exception
            self.log.error("Current working directory doesn't exist.")
            raise

        # ensure even default IPYTHONDIR exists
        if not os.path.exists(self.ipython_dir):
            self._ipython_dir_changed('ipython_dir', self.ipython_dir, self.ipython_dir)

    #-------------------------------------------------------------------------
    # Various stages of Application creation
    #------------------------------------------------------------------------- 
Example #7
Source File: prompts.py    From Computable with MIT License 6 votes vote down vote up
def cwd_filt2(depth):
    """Return the last depth elements of the current working directory.

    $HOME is always replaced with '~'.
    If depth==0, the full path is returned."""

    full_cwd = os.getcwdu()
    cwd = full_cwd.replace(HOME,"~").split(os.sep)
    if '~' in cwd and len(cwd) == depth+1:
        depth += 1
    drivepart = ''
    if sys.platform == 'win32' and len(cwd) > depth:
        drivepart = os.path.splitdrive(full_cwd)[0]
    out = drivepart + '/'.join(cwd[-depth:])

    return out or os.sep

#-----------------------------------------------------------------------------
# Prompt classes
#----------------------------------------------------------------------------- 
Example #8
Source File: test_magic.py    From Computable with MIT License 6 votes vote down vote up
def test_dirops():
    """Test various directory handling operations."""
    # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/')
    curpath = os.getcwdu
    startdir = os.getcwdu()
    ipdir = os.path.realpath(_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
Source File: test_completer.py    From Computable with MIT License 6 votes vote down vote up
def test_local_file_completions():
    ip = get_ipython()
    cwd = os.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
Source File: test_fixers.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_basic(self):
        b = """os.getcwdu"""
        a = """os.getcwd"""
        self.check(b, a)

        b = """os.getcwdu()"""
        a = """os.getcwd()"""
        self.check(b, a)

        b = """meth = os.getcwdu"""
        a = """meth = os.getcwd"""
        self.check(b, a)

        b = """os.getcwdu(args)"""
        a = """os.getcwd(args)"""
        self.check(b, a) 
Example #11
Source File: test_run.py    From Computable with MIT License 6 votes vote down vote up
def setUp(self):
        self.package = package = 'tmp{0}'.format(repr(random.random())[2:])
        """Temporary valid python package name."""

        self.value = int(random.random() * 10000)

        self.tempdir = TemporaryDirectory()
        self.__orig_cwd = os.getcwdu()
        sys.path.insert(0, self.tempdir.name)

        self.writefile(os.path.join(package, '__init__.py'), '')
        self.writefile(os.path.join(package, 'sub.py'), """
        x = {0!r}
        """.format(self.value))
        self.writefile(os.path.join(package, 'relative.py'), """
        from .sub import x
        """)
        self.writefile(os.path.join(package, 'absolute.py'), """
        from {0}.sub import x
        """.format(package)) 
Example #12
Source File: test_unicode_file.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def _do_directory(self, make_name, chdir_name, encoded):
        if os.path.isdir(make_name):
            os.rmdir(make_name)
        os.mkdir(make_name)
        try:
            with change_cwd(chdir_name):
                if not encoded:
                    cwd_result = os.getcwdu()
                    name_result = make_name
                else:
                    cwd_result = os.getcwd().decode(TESTFN_ENCODING)
                    name_result = make_name.decode(TESTFN_ENCODING)

                cwd_result = unicodedata.normalize("NFD", cwd_result)
                name_result = unicodedata.normalize("NFD", name_result)

                self.assertEqual(os.path.basename(cwd_result),name_result)
        finally:
            os.rmdir(make_name)

    # The '_test' functions 'entry points with params' - ie, what the
    # top-level 'test' functions would be if they could take params 
Example #13
Source File: frontend.py    From faces with GNU General Public License v2.0 6 votes vote down vote up
def make_paths_absolute(pathdict, keys, base_path=None):
    """
    Interpret filesystem path settings relative to the `base_path` given.

    Paths are values in `pathdict` whose keys are in `keys`.  Get `keys` from
    `OptionParser.relative_path_settings`.
    """
    if base_path is None:
        base_path = os.getcwdu() # type(base_path) == unicode
        # to allow combining non-ASCII cwd with unicode values in `pathdict`
    for key in keys:
        if key in pathdict:
            value = pathdict[key]
            if isinstance(value, list):
                value = [make_one_path_absolute(base_path, path)
                         for path in value]
            elif value:
                value = make_one_path_absolute(base_path, value)
            pathdict[key] = value 
Example #14
Source File: process.py    From Computable with MIT License 6 votes vote down vote up
def abbrev_cwd():
    """ Return abbreviated version of cwd, e.g. d:mydir """
    cwd = os.getcwdu().replace('\\','/')
    drivepart = ''
    tail = cwd
    if sys.platform == 'win32':
        if len(cwd) < 4:
            return cwd
        drivepart,tail = os.path.splitdrive(cwd)


    parts = tail.split('/')
    if len(parts) > 2:
        tail = '/'.join(parts[-2:])

    return (drivepart + (
        cwd == '/' and '/' or tail)) 
Example #15
Source File: osm.py    From Computable with MIT License 5 votes vote down vote up
def pwd(self, parameter_s=''):
        """Return the current working directory path.

        Examples
        --------
        ::

          In [9]: pwd
          Out[9]: '/home/tsuser/sprint/ipython'
        """
        return os.getcwdu() 
Example #16
Source File: ntpath.py    From oss-ftp with MIT License 5 votes vote down vote up
def abspath(path):
        """Return the absolute version of a path."""
        if not isabs(path):
            if isinstance(path, unicode):
                cwd = os.getcwdu()
            else:
                cwd = os.getcwd()
            path = join(cwd, path)
        return normpath(path) 
Example #17
Source File: interactiveshell.py    From Computable with MIT License 5 votes vote down vote up
def init_instance_attrs(self):
        self.more = False

        # command compiler
        self.compile = CachingCompiler()

        # Make an empty namespace, which extension writers can rely on both
        # existing and NEVER being used by ipython itself.  This gives them a
        # convenient location for storing additional information and state
        # their extensions may require, without fear of collisions with other
        # ipython names that may develop later.
        self.meta = Struct()

        # Temporary files used for various purposes.  Deleted at exit.
        self.tempfiles = []

        # Keep track of readline usage (later set by init_readline)
        self.has_readline = False

        # keep track of where we started running (mainly for crash post-mortem)
        # This is not being used anywhere currently.
        self.starting_dir = os.getcwdu()

        # Indentation management
        self.indent_current_nsp = 0

        # Dict to track post-execution functions that have been registered
        self._post_execute = {} 
Example #18
Source File: ipdoctest.py    From Computable with MIT License 5 votes vote down vote up
def runTest(self):
        test = self._dt_test
        runner = self._dt_runner

        old = sys.stdout
        new = StringIO()
        optionflags = self._dt_optionflags

        if not (optionflags & REPORTING_FLAGS):
            # The option flags don't include any reporting flags,
            # so add the default reporting flags
            optionflags |= _unittest_reportflags

        try:
            # Save our current directory and switch out to the one where the
            # test was originally created, in case another doctest did a
            # directory change.  We'll restore this in the finally clause.
            curdir = os.getcwdu()
            #print 'runTest in dir:', self._ori_dir  # dbg
            os.chdir(self._ori_dir)

            runner.DIVIDER = "-"*70
            failures, tries = runner.run(test,out=new.write,
                                         clear_globs=False)
        finally:
            sys.stdout = old
            os.chdir(curdir)

        if failures:
            raise self.failureException(self.format_failure(new.getvalue())) 
Example #19
Source File: osm.py    From Computable with MIT License 5 votes vote down vote up
def pushd(self, parameter_s=''):
        """Place the current dir on stack and change directory.

        Usage:\\
          %pushd ['dirname']
        """

        dir_s = self.shell.dir_stack
        tgt = os.path.expanduser(unquote_filename(parameter_s))
        cwd = os.getcwdu().replace(self.shell.home_dir,'~')
        if tgt:
            self.cd(parameter_s)
        dir_s.insert(0,cwd)
        return self.shell.magic('dirs') 
Example #20
Source File: clustermanager.py    From Computable with MIT License 5 votes vote down vote up
def update_profiles(self):
        """List all profiles in the ipython_dir and cwd.
        """
        for path in [get_ipython_dir(), os.getcwdu()]:
            for profile in list_profiles_in(path):
                pd = self.get_profile_dir(profile, path)
                if profile not in self.profiles:
                    self.log.debug("Adding cluster profile '%s'" % profile)
                    self.profiles[profile] = {
                        'profile': profile,
                        'profile_dir': pd,
                        'status': 'stopped'
                    } 
Example #21
Source File: _path.py    From Computable with MIT License 5 votes vote down vote up
def relpath(self):
        """ Return this path as a relative path,
        based from the current working directory.
        """
        cwd = self.__class__(os.getcwdu())
        return cwd.relpathto(self) 
Example #22
Source File: _path.py    From Computable with MIT License 5 votes vote down vote up
def getcwd(cls):
        """ Return the current working directory as a path object. """
        return cls(os.getcwdu()) 
Example #23
Source File: workflow.py    From wechat-alfred-workflow with MIT License 5 votes vote down vote up
def workflowdir(self):
        """Path to workflow's root directory (where ``info.plist`` is).

        :returns: full path to workflow root directory
        :rtype: ``unicode``

        """
        if not self._workflowdir:
            # Try the working directory first, then the directory
            # the library is in. CWD will be the workflow root if
            # a workflow is being run in Alfred
            candidates = [
                os.path.abspath(os.getcwdu()),
                os.path.dirname(os.path.abspath(os.path.dirname(__file__)))]

            # climb the directory tree until we find `info.plist`
            for dirpath in candidates:

                # Ensure directory path is Unicode
                dirpath = self.decode(dirpath)

                while True:
                    if os.path.exists(os.path.join(dirpath, 'info.plist')):
                        self._workflowdir = dirpath
                        break

                    elif dirpath == '/':
                        # no `info.plist` found
                        break

                    # Check the parent directory
                    dirpath = os.path.dirname(dirpath)

                # No need to check other candidates
                if self._workflowdir:
                    break

            if not self._workflowdir:
                raise IOError("'info.plist' not found in directory tree")

        return self._workflowdir 
Example #24
Source File: _process_win32.py    From Computable with MIT License 5 votes vote down vote up
def __enter__(self):
        self.path = os.getcwdu()
        self.is_unc_path = self.path.startswith(r"\\")
        if self.is_unc_path:
            # change to c drive (as cmd.exe cannot handle UNC addresses)
            os.chdir("C:")
            return self.path
        else:
            # We return None to signal that there was no change in the working
            # directory
            return None 
Example #25
Source File: terminal.py    From Computable with MIT License 5 votes vote down vote up
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 = os.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 
Example #26
Source File: ntpath.py    From oss-ftp with MIT License 5 votes vote down vote up
def abspath(path):
        """Return the absolute version of a path."""

        if path: # Empty path must return current working directory.
            try:
                path = _getfullpathname(path)
            except WindowsError:
                pass # Bad path - return unchanged.
        elif isinstance(path, unicode):
            path = os.getcwdu()
        else:
            path = os.getcwd()
        return normpath(path)

# realpath is a no-op on systems without islink support 
Example #27
Source File: _process_win32_controller.py    From Computable with MIT License 5 votes vote down vote up
def __enter__(self):
        self.path = os.getcwdu()
        self.is_unc_path = self.path.startswith(r"\\")
        if self.is_unc_path:
            # change to c drive (as cmd.exe cannot handle UNC addresses)
            os.chdir("C:")
            return self.path
        else:
            # We return None to signal that there was no change in the working
            # directory
            return None 
Example #28
Source File: baseapp.py    From Computable with MIT License 5 votes vote down vote up
def to_work_dir(self):
        wd = self.work_dir
        if unicode(wd) != os.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 #29
Source File: test_fixers.py    From Computable with MIT License 5 votes vote down vote up
def test_multilation(self):
        b = """os .getcwdu()"""
        a = """os .getcwd()"""
        self.check(b, a)

        b = """os.  getcwdu"""
        a = """os.  getcwd"""
        self.check(b, a)

        b = """os.getcwdu (  )"""
        a = """os.getcwd (  )"""
        self.check(b, a) 
Example #30
Source File: test_prompts.py    From Computable with MIT License 5 votes vote down vote up
def test_render_unicode_cwd(self):
        save = os.getcwdu()
        with TemporaryDirectory(u'ünicødé') as td:
            os.chdir(td)
            self.pm.in_template = r'\w [\#]'
            p = self.pm.render('in', color=False)
            self.assertEqual(p, u"%s [%i]" % (os.getcwdu(), ip.execution_count))
        os.chdir(save)