Check if a given path is a virtual environment's root.

    This is done by checking if the directory contains a Python executable in
    its bin/Scripts directory. Not technically correct, but good enough for
    general usage.
420576
def is_virtual_environment(path):
    
    if not path.is_dir():
        return False
    for bindir_name in ('bin', 'Scripts'):
        for python in path.joinpath(bindir_name).glob('python*'):
            try:
                exeness = python.is_file() and os.access(str(python), os.X_OK)
            except OSError:
                exeness = False
            if exeness:
                return True
    return False
588962
def __root_path(self):
        
        if self.root_path is not None:
            if os.path.isdir(self.root_path):
                sys.path.append(self.root_path)
                return
            raise RuntimeError('EverNode requires a valid root path.'
                               ' Directory: %s does not exist'
                               % (self.root_path))
1259075
def is_executable_file(path):
    
    # follow symlinks,
    fpath = os.path.realpath(path)

    if not os.path.isfile(fpath):
        # non-files (directories, fifo, etc.)
        return False

    mode = os.stat(fpath).st_mode

    if (sys.platform.startswith('sunos')
            and os.getuid() == 0):
        # When root on Solaris, os.X_OK is True for *all* files, irregardless
        # of their executability -- instead, any permission bit of any user,
        # group, or other is fine enough.
        #
        # (This may be true for other "Unix98" OS's such as HP-UX and AIX)
        return bool(mode & (stat.S_IXUSR |
                            stat.S_IXGRP |
                            stat.S_IXOTH))

    return os.access(fpath, os.X_OK)
615192
def is_dir(self):
        
        try:
            return S_ISDIR(self.stat().st_mode)
        except OSError as e:
            if e.errno not in (ENOENT, ENOTDIR):
                raise
            # Path doesn't exist or is a broken symlink
            # (see https://bitbucket.org/pitrou/pathlib/issue/12/)
            return False
750893
def is_role(path):
    
    seems_legit = False
    for folder in c.ANSIBLE_FOLDERS:
        if os.path.exists(os.path.join(path, folder)):
            seems_legit = True

    return seems_legit
622598
def is_installed(prog):
    """"""
    with open(os.devnull, 'w') as devnull:
        try:
            if os.name == 'nt':
                retcode = subprocess.call(['where', prog], stdout=devnull)
            else:
                retcode = subprocess.call(['which', prog], stdout=devnull)
        except OSError as e:
            # If where or which doesn't exist, a "ENOENT" error will occur (The
            # FileNotFoundError subclass on Python 3).
            if e.errno != errno.ENOENT:
                raise
            retcode = 1

    return retcode == 0
146525
def _is_svc(svc_path):
    '''
    
    '''
    run_file = os.path.join(svc_path, 'run')
    if (os.path.exists(svc_path)
         and os.path.exists(run_file)
         and os.access(run_file, os.X_OK)):
        return True
    return False
803350
function checkPython () {
    log.verbose('check python', 'checking for Python executable "%s" in the PATH', python)
    which(python, function (err, execPath) {
      if (err) {
        log.verbose('`which` failed', python, err)
        if (python === 'python2') {
          python = 'python'
          return checkPython()
        }
        if (win) {
          guessPython()
        } else {
          failNoPython()
        }
      } else {
        log.verbose('`which` succeeded', python, execPath)
        // Found the `python` exceutable, and from now on we use it explicitly.
        // This solves #667 and #750 (`execFile` won't run batch files
        // (*.cmd, and *.bat))
        python = execPath
        checkPythonVersion()
      }
    })
  }
1319371
def check_path(path, create=False):
    
    if not os.path.exists(path):
        if create:
            os.makedirs(path)
            return os.path.exists(path)
        else:
            return False

    return True
1015799
def _virtualenv_sys(venv_path):
    ""
    executable = os.path.join(venv_path, env_bin_dir, 'python')
    # Must use "executable" as the first argument rather than as the
    # keyword argument "executable" to get correct value from sys.path
    p = subprocess.Popen([executable,
        '-c', 'import sys;'
              'print (sys.version[:3]);'
              'print ("\\n".join(sys.path));'],
        env={},
        stdout=subprocess.PIPE)
    stdout, err = p.communicate()
    assert not p.returncode and stdout
    lines = stdout.decode('utf-8').splitlines()
    return lines[0], list(filter(bool, lines[1:]))
1219937
def is_valid_dir(path):
    '''  '''
    return os.path.exists(path) and os.path.isdir(path)
868420
def is_absolute_path (path):
    """"""
    if os.name == 'nt':
        if re.search(r"^[a-zA-Z]:", path):
            return True
        path = path.replace("\\", "/")
    return path.startswith("/")
22368
def restart_in_venv(venv, base, site_packages, args):
    
    if base and not os.path.isabs(venv) and not venv.startswith('~'):
        base = os.path.expanduser(base)
        # ensure we have an abs basepath at this point:
        #    a relative one makes no sense (or does it?)
        if os.path.isabs(base):
            venv = os.path.join(base, venv)

    if venv.startswith('~'):
        venv = os.path.expanduser(venv)

    if not os.path.exists(venv):
        try:
            import virtualenv
        except ImportError:
            print('The virtual environment does not exist: %s' % venv)
            print('and virtualenv is not installed, so a new environment cannot be created')
            sys.exit(3)
        print('Creating new virtualenv environment in %s' % venv)
        virtualenv.logger = logger
        logger.indent += 2
        virtualenv.create_environment(venv, site_packages=site_packages)
    if sys.platform == 'win32':
        python = os.path.join(venv, 'Scripts', 'python.exe')
        # check for bin directory which is used in buildouts
        if not os.path.exists(python):
            python = os.path.join(venv, 'bin', 'python.exe')
    else:
        python = os.path.join(venv, 'bin', 'python')
    if not os.path.exists(python):
        python = venv
    if not os.path.exists(python):
        raise BadCommand('Cannot find virtual environment interpreter at %s' % python)
    base = os.path.dirname(os.path.dirname(python))
    file = os.path.join(os.path.dirname(__file__), 'runner.py')
    if file.endswith('.pyc'):
        file = file[:-1]
    proc = subprocess.Popen(
        [python, file] + args + [base, '___VENV_RESTART___'])
    proc.wait()
    sys.exit(proc.returncode)
524724
def _path_is_executable_others(path):
    '''
    
    '''
    prevpath = None
    while path and path != prevpath:
        try:
            if not os.stat(path).st_mode & stat.S_IXOTH:
                return False
        except OSError:
            return False
        prevpath = path
        path, _ = os.path.split(path)
    return True
1130275
def FileEntryExistsByPathSpec(self, path_spec):
    
    tsk_vs_part, _ = tsk_partition.GetTSKVsPartByPathSpec(
        self._tsk_volume, path_spec)

    # The virtual root file has not corresponding TSK volume system part object
    # but should have a location.
    if tsk_vs_part is None:
      location = getattr(path_spec, 'location', None)
      return location is not None and location == self.LOCATION_ROOT

    return True
311568
def _check_env(fn):
    
    def decorator(*args, **kwargs):
        # If no directory is provided, set the default one
        resultdir = kwargs.get("--env", SYMLINK_NAME)
        # Check if the env file exists
        env_path = os.path.join(resultdir, "env")
        if not os.path.isfile(env_path):
            raise Exception("The file %s does not exist." % env_path)

        # Proceeds with the function execution
        return fn(*args, **kwargs)
    return decorator
739454
def in_venv():
    
    global _in_venv
    if _in_venv is not None:
        return _in_venv

    if not (os.path.isfile(ORIG_PREFIX_TXT) or os.path.isfile(PY_VENV_CFG)):
        logger.debug("in_venv no orig_prefix_txt [%s]", ORIG_PREFIX_TXT)
        logger.debug("in_venv no py_venv_cfg [%s]", PY_VENV_CFG)
        # TODO - check this is actually valid !
        _in_venv = False
        return _in_venv

    if 'VIRTUAL_ENV' in os.environ:
        logger.debug("in_venv VIRTUAL_ENV set.")
        _in_venv = True
    else:
        # Find first python in path ... if its not this one,
        # ...we are in a different python
        python = basename(sys.executable)
        for p in os.environ['PATH'].split(os.pathsep):
            py_path = join(p, python)
            if isfile(py_path):
                logger.debug("in_venv py_at [%s] return: %s", (py_path, sys.executable != py_path))
                _in_venv = sys.executable != py_path
                break

    return _in_venv