Python errno.ENOENT Examples

The following are 30 code examples of errno.ENOENT(). 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 errno , or try the search function .
Example #1
Source File: remote_host_helper.py    From Zopkio with Apache License 2.0 6 votes vote down vote up
def copy_dir(ftp, filename, outputdir, prefix, pattern=''):
  """
  Recursively copy a directory flattens the output into a single directory but
  prefixes the files with the path from the original input directory
  :param ftp:
  :param filename:
  :param outputdir:
  :param prefix:
  :param pattern: a regex pattern for files to match (by default matches everything)
  :return:
  """
  try:
    mode = ftp.stat(filename).st_mode
  except IOError, e:
    if e.errno == errno.ENOENT:
      logger.error("Log file " + filename + " does not exist")
      pass 
Example #2
Source File: file.py    From gnocchi with Apache License 2.0 6 votes vote down vote up
def _delete_measures_files_for_metric(self, metric_id, files):
        for f in files:
            try:
                os.unlink(self._build_measure_path(metric_id, f))
            except OSError as e:
                # Another process deleted it in the meantime, no prob'
                if e.errno != errno.ENOENT:
                    raise
        try:
            os.rmdir(self._build_measure_path(metric_id))
        except OSError as e:
            # ENOENT: ok, it has been removed at almost the same time
            #         by another process
            # ENOTEMPTY: ok, someone pushed measure in the meantime,
            #            we'll delete the measures and directory later
            # EEXIST: some systems use this instead of ENOTEMPTY
            if e.errno not in (errno.ENOENT, errno.ENOTEMPTY, errno.EEXIST):
                raise 
Example #3
Source File: versioneer.py    From aospy with Apache License 2.0 6 votes vote down vote up
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
                env=None):
    """Call the given command(s)."""
    assert isinstance(commands, list)
    p = None
    for c in commands:
        try:
            dispcmd = str([c] + args)
            # remember shell=False, so use git.cmd on windows, not just git
            p = subprocess.Popen([c] + args, cwd=cwd, env=env,
                                 stdout=subprocess.PIPE,
                                 stderr=(subprocess.PIPE if hide_stderr
                                         else None))
            break
        except EnvironmentError:
            e = sys.exc_info()[1]
            if e.errno == errno.ENOENT:
                continue
            if verbose:
                print("unable to run %s" % dispcmd)
                print(e)
            return None, None
    else:
        if verbose:
            print("unable to find command, tried %s" % (commands,))
        return None, None
    stdout = p.communicate()[0].strip()
    if sys.version_info[0] >= 3:
        stdout = stdout.decode()
    if p.returncode != 0:
        if verbose:
            print("unable to run %s (error)" % dispcmd)
            print("stdout was %s" % stdout)
        return None, p.returncode
    return stdout, p.returncode 
Example #4
Source File: proto_support.py    From recipes-py with Apache License 2.0 6 votes vote down vote up
def _check_digest(proto_package, dgst):
  """Checks protos installed in `{proto_package_path}/PB`.

  Args:
    * proto_package_base (str) - The absolute path to the folder where we will
      look for '.../PB/csum
    * dgst (str) - The digest of the proto files which we believe need to be
      built.

  Returns True iff csum matches dgst.
  """
  try:
    csum_path = os.path.join(proto_package, 'PB', 'csum')
    with open(csum_path, 'rb') as cur_dgst_f:
      return cur_dgst_f.read() == dgst
  except (OSError, IOError) as exc:
    if exc.errno != errno.ENOENT:
      raise 
Example #5
Source File: file.py    From gnocchi with Apache License 2.0 6 votes vote down vote up
def _store_new_measures(self, metric_id, data):
        tmpfile = tempfile.NamedTemporaryFile(
            prefix='gnocchi', dir=self.basepath_tmp,
            delete=False)
        tmpfile.write(data)
        tmpfile.close()
        path = self._build_measure_path(metric_id, True)
        while True:
            try:
                os.rename(tmpfile.name, path)
                break
            except OSError as e:
                if e.errno != errno.ENOENT:
                    raise
                try:
                    os.mkdir(self._build_measure_path(metric_id))
                except OSError as e:
                    # NOTE(jd) It's possible that another process created the
                    # path just before us! In this case, good for us, let's do
                    # nothing then! (see bug #1475684)
                    if e.errno != errno.EEXIST:
                        raise 
Example #6
Source File: ps_mem.py    From pywren-ibm-cloud with Apache License 2.0 6 votes vote down vote up
def verify_environment(pids_to_show):
    if os.geteuid() != 0 and not pids_to_show:
        sys.stderr.write("Sorry, root permission required, or specify pids with -p\n")
        sys.stderr.close()
        sys.exit(1)

    try:
        kernel_ver()
    except (IOError, OSError):
        val = sys.exc_info()[1]
        if val.errno == errno.ENOENT:
            sys.stderr.write(
              "Couldn't access " + proc.path('') + "\n"
              "Only GNU/Linux and FreeBSD (with linprocfs) are supported\n")
            sys.exit(2)
        else:
            raise 
Example #7
Source File: deployer.py    From Zopkio with Apache License 2.0 6 votes vote down vote up
def fetch_logs_from_host(hostname, install_path, prefix, logs, directory, pattern):
    """ Static method Copies logs from specified host on the specified install path

    :Parameter hostname the remote host from where we need to fetch the logs
    :Parameter install_path path where the app is installed
    :Parameter prefix prefix used to copy logs. Generall the unique_id of process
    :Parameter logs a list of logs given by absolute path from the remote host
    :Parameter directory the local directory to store the copied logs
    :Parameter pattern a pattern to apply to files to restrict the set of logs copied
    """
    if hostname is not None:
      with get_sftp_client(hostname, username=runtime.get_username(), password=runtime.get_password()) as ftp:
        for f in logs:
          try:
            mode = ftp.stat(f).st_mode
          except IOError, e:
            if e.errno == errno.ENOENT:
              logger.error("Log file " + f + " does not exist on " + hostname)
              pass
          else:
            copy_dir(ftp, f, directory, prefix)
        if install_path is not None:
          copy_dir(ftp, install_path, directory, prefix, pattern) 
Example #8
Source File: pdosq.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def safe_remove(path):
    """
    Remove a file or silently pass if the file does not exist.

    This function has the same effect as os.remove but suppresses the error if
    the file did not exist. Notably, it must not be used to remove directories.

    Returns True if a file was removed or False if no file was removed.
    """
    try:
        os.remove(path)
        return True
    except OSError as err:
        # Suppress the exception if it is a file not found error.
        # Otherwise, re-raise the exception.
        if err.errno != errno.ENOENT:
            raise

    return False 
Example #9
Source File: base.py    From calmjs with GNU General Public License v2.0 6 votes vote down vote up
def _get_exec_binary(binary, kw):
    """
    On win32, the subprocess module can only reliably resolve the
    target binary if it's actually a binary; as for a Node.js script
    it seems to only work iff shell=True was specified, presenting
    a security risk.  Resolve the target manually through which will
    account for that.

    The kw argument is the keyword arguments that will be passed into
    whatever respective subprocess.Popen family of methods.  The PATH
    environment variable will be used if available.
    """

    binary = which(binary, path=kw.get('env', {}).get('PATH'))
    if binary is None:
        raise_os_error(errno.ENOENT)
    return binary 
Example #10
Source File: fileutil.py    From recipes-py with Apache License 2.0 5 votes vote down vote up
def _Remove(path):
  try:
    os.remove(path)
  except OSError as e:
    if e.errno != errno.ENOENT:
      raise 
Example #11
Source File: support.py    From verge3d-blender-addon with GNU General Public License v3.0 5 votes vote down vote up
def rmdir(dirname):
    try:
        _rmdir(dirname)
    except OSError as error:
        # The directory need not exist.
        if error.errno != errno.ENOENT:
            raise 
Example #12
Source File: support.py    From verge3d-blender-addon with GNU General Public License v3.0 5 votes vote down vote up
def rmtree(path):
    try:
        _rmtree(path)
    except OSError as error:
        if error.errno != errno.ENOENT:
            raise 
Example #13
Source File: temporarydir.py    From me-ica with GNU Lesser General Public License v2.1 5 votes vote down vote up
def __init__(self, suffix="", prefix=template, dir=None):
        self._closed = False
        self._ENOENT = errno.ENOENT
        self.name = None # Handle mkdtemp throwing an exception
        self.name = mkdtemp(suffix, prefix, dir) 
Example #14
Source File: test_env.py    From recipes-py with Apache License 2.0 5 votes vote down vote up
def tearDown(self):
    if LEAK and not self._resultForDoCleanups.wasSuccessful():
      LEAKED_DIRS.extend(self.nuke_dirs)
      LEAKED_FILES.extend(self.nuke_files)
      return

    for to_nuke in self.nuke_dirs:
      shutil.rmtree(to_nuke, ignore_errors=True)
    for to_nuke in self.nuke_files:
      try:
        os.unlink(to_nuke)
      except OSError as ex:
        if ex.errno != errno.ENOENT:
          raise 
Example #15
Source File: fileutil.py    From recipes-py with Apache License 2.0 5 votes vote down vote up
def _RmGlob(file_wildcard, root, include_hidden):
  """Removes files matching 'file_wildcard' in root and its subdirectories, if
  any exists.

  An exception is thrown if root doesn't exist."""
  wildcard = os.path.join(os.path.realpath(root), file_wildcard)
  for item in glob2.glob(wildcard, include_hidden=include_hidden):
    try:
      os.remove(item)
    except OSError, e:
      if e.errno != errno.ENOENT:
        raise 
Example #16
Source File: definition.py    From recipes-py with Apache License 2.0 5 votes vote down vote up
def parse_warning_definitions(file_path):
  """Parse the warning definition file at the given absolute path. The file
  content is expected to be in text proto format of warning.DefinitionCollection
  proto message. Duplicate warning names will be raised. Each warning definition
  will be validated. The conditions are documented in warning.proto.

  Args:
    * file_path (str) - Absolute path to warning definition file

  Returns a dict of warning name to warning.Definition proto message instance
  """
  raw_text = ''
  try:
    with open(file_path, encoding='utf-8') as f:
      raw_text = f.read()
  except IOError as ex:
    if ex.errno == errno.ENOENT:
      # No warning defined
      return {}
    raise ex

  from PB.recipe_engine.warning import DefinitionCollection
  definition_collection = textpb.Parse(raw_text, DefinitionCollection())
  definitions = list(definition_collection.warning)

  if definition_collection.HasField('monorail_bug_default'):
    _populate_monorail_bug_default_fields(
      definitions, definition_collection.monorail_bug_default)

  ret = {}
  for definition in definitions:
    if definition.name in ret:
      raise ValueError(
        'Found warning definitions with duplicate name: %s' % definition.name)
    _validate(definition)
    ret[definition.name] = definition
  return ret 
Example #17
Source File: api.py    From recipes-py with Apache License 2.0 5 votes vote down vote up
def _rmfile(p, _win_read_only_unset=False):  # pragma: no cover
  """Deletes a file, even a read-only one on Windows."""
  try:
    os.remove(p)
  except OSError as e:
    if sys.platform == 'win32' and not _win_read_only_unset:
      # Try to remove the read-only bit and remove again.
      os.chmod(p, 0777)
      _rmfile(p, _win_read_only_unset=True)
    elif e.errno != errno.ENOENT:
      raise 
Example #18
Source File: api.py    From recipes-py with Apache License 2.0 5 votes vote down vote up
def result(self, presentation, test):
    assert self._backing_file
    ret = None
    if test.enabled:
      self._backing_file = None
      # Use None to indicate that `result()` should behave as if the backing
      # file is missing. Only valid if `leak_to` is None; otherwise, the
      # backing file is a temporary file created in `render()` that is
      # guaranteed to exist unless the recipe or the step subprocess explicitly
      # removes it before accessing its contents.
      if self.leak_to and test.data is None:
        return None
      with contextlib.closing(cStringIO.StringIO(test.data or '')) as infile:
        ret = self.read_decoded_data(infile)
    else:  # pragma: no cover
      try:
        with open(self._backing_file, 'rb') as f:
          ret = self.read_decoded_data(f)
      except IOError as e:
        if e.errno != errno.ENOENT:
          raise
      finally:
        if not self.leak_to:
          _rmfile(self._backing_file)
        self._backing_file = None

    if ret is not None and (
        self.add_output_log is True or
        (self.add_output_log == 'on_failure' and
         presentation.status != 'SUCCESS')):
      presentation.logs[self.label] = ret.splitlines()

    return ret 
Example #19
Source File: os_capability_linux.py    From zun with Apache License 2.0 5 votes vote down vote up
def get_mem_numa_info(self):
        try:
            output = utils.execute('numactl', '-H')
        except OSError as e:
            if e.errno == errno.ENOENT:
                LOG.info("The program 'numactl' is not installed.")
                return []
            else:
                raise

        sizes = re.findall(r"size\: \d*", str(output))
        mem_numa = []
        for size in sizes:
            mem_numa.append(int(size.split(' ')[1]))
        return mem_numa 
Example #20
Source File: support.py    From verge3d-blender-addon with GNU General Public License v3.0 5 votes vote down vote up
def unlink(filename):
    try:
        _unlink(filename)
    except OSError as error:
        # The filename need not exist.
        if error.errno not in (errno.ENOENT, errno.ENOTDIR):
            raise 
Example #21
Source File: didyoumean_internal.py    From DidYouMean-Python with MIT License 5 votes vote down vote up
def get_io_os_error_sugg(value, frame, groups):
    """Get suggestions for IOError/OSError exception."""
    # https://www.python.org/dev/peps/pep-3151/
    del frame, groups  # unused param
    err, _ = value.args
    errnos = {
        errno.ENOENT: suggest_if_file_does_not_exist,
        errno.ENOTDIR: suggest_if_file_is_not_dir,
        errno.EISDIR: suggest_if_file_is_dir,
    }
    return errnos.get(err, lambda x: [])(value) 
Example #22
Source File: _version.py    From landmarkerio-server with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
    assert isinstance(commands, list)
    p = None
    for c in commands:
        try:
            dispcmd = str([c] + args)
            # remember shell=False, so use git.cmd on windows, not just git
            p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,
                                 stderr=(subprocess.PIPE if hide_stderr
                                         else None))
            break
        except EnvironmentError:
            e = sys.exc_info()[1]
            if e.errno == errno.ENOENT:
                continue
            if verbose:
                print("unable to run %s" % dispcmd)
                print(e)
            return None
    else:
        if verbose:
            print("unable to find command, tried %s" % (commands,))
        return None
    stdout = p.communicate()[0].strip()
    if sys.version_info[0] >= 3:
        stdout = stdout.decode()
    if p.returncode != 0:
        if verbose:
            print("unable to run %s (error)" % dispcmd)
        return None
    return stdout 
Example #23
Source File: versioneer.py    From landmarkerio-server with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
    assert isinstance(commands, list)
    p = None
    for c in commands:
        try:
            dispcmd = str([c] + args)
            # remember shell=False, so use git.cmd on windows, not just git
            p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,
                                 stderr=(subprocess.PIPE if hide_stderr
                                         else None))
            break
        except EnvironmentError:
            e = sys.exc_info()[1]
            if e.errno == errno.ENOENT:
                continue
            if verbose:
                print("unable to run %s" % dispcmd)
                print(e)
            return None
    else:
        if verbose:
            print("unable to find command, tried %s" % (commands,))
        return None
    stdout = p.communicate()[0].strip()
    if sys.version_info[0] >= 3:
        stdout = stdout.decode()
    if p.returncode != 0:
        if verbose:
            print("unable to run %s (error)" % dispcmd)
        return None
    return stdout 
Example #24
Source File: support.py    From jawfish with MIT License 5 votes vote down vote up
def rmtree(path):
    try:
        _rmtree(path)
    except OSError as error:
        if error.errno != errno.ENOENT:
            raise 
Example #25
Source File: support.py    From jawfish with MIT License 5 votes vote down vote up
def unlink(filename):
    try:
        _unlink(filename)
    except OSError as error:
        # The filename need not exist.
        if error.errno not in (errno.ENOENT, errno.ENOTDIR):
            raise 
Example #26
Source File: ssl_.py    From jawfish with MIT License 5 votes vote down vote up
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
                    ca_certs=None, server_hostname=None,
                    ssl_version=None, ciphers=None, ssl_context=None):
    """
    All arguments except for server_hostname and ssl_context have the same
    meaning as they do when using :func:`ssl.wrap_socket`.

    :param server_hostname:
        When SNI is supported, the expected hostname of the certificate
    :param ssl_context:
        A pre-made :class:`SSLContext` object. If none is provided, one will
        be created using :func:`create_urllib3_context`.
    :param ciphers:
        A string of ciphers we wish the client to support. This is not
        supported on Python 2.6 as the ssl module does not support it.
    """
    context = ssl_context
    if context is None:
        context = create_urllib3_context(ssl_version, cert_reqs,
                                         ciphers=ciphers)

    if ca_certs:
        try:
            context.load_verify_locations(ca_certs)
        except IOError as e:  # Platform-specific: Python 2.6, 2.7, 3.2
            raise SSLError(e)
        # Py33 raises FileNotFoundError which subclasses OSError
        # These are not equivalent unless we check the errno attribute
        except OSError as e:  # Platform-specific: Python 3.3 and beyond
            if e.errno == errno.ENOENT:
                raise SSLError(e)
            raise
    if certfile:
        context.load_cert_chain(certfile, keyfile)
    if HAS_SNI:  # Platform-specific: OpenSSL with enabled SNI
        return context.wrap_socket(sock, server_hostname=server_hostname)
    return context.wrap_socket(sock) 
Example #27
Source File: handlers.py    From jawfish with MIT License 5 votes vote down vote up
def emit(self, record):
        """
        Emit a record.

        First check if the underlying file has changed, and if it
        has, close the old stream and reopen the file to get the
        current stream.
        """
        # Reduce the chance of race conditions by stat'ing by path only
        # once and then fstat'ing our new fd if we opened a new log stream.
        # See issue #14632: Thanks to John Mulligan for the problem report
        # and patch.
        try:
            # stat the file by path, checking for existence
            sres = os.stat(self.baseFilename)
        except OSError as err:
            if err.errno == errno.ENOENT:
                sres = None
            else:
                raise
        # compare file system stat with that of our stream file handle
        if not sres or sres[ST_DEV] != self.dev or sres[ST_INO] != self.ino:
            if self.stream is not None:
                # we have an open file handle, clean it up
                self.stream.flush()
                self.stream.close()
                # open a new file handle and get new stat info from that fd
                self.stream = self._open()
                self._statstream()
        logging.FileHandler.emit(self, record) 
Example #28
Source File: tempfile.py    From jawfish with MIT License 5 votes vote down vote up
def _get_default_tempdir():
    """Calculate the default directory to use for temporary files.
    This routine should be called exactly once.

    We determine whether or not a candidate temp dir is usable by
    trying to create and write to a file in that directory.  If this
    is successful, the test file is deleted.  To prevent denial of
    service, the name of the test file must be randomized."""

    namer = _RandomNameSequence()
    dirlist = _candidate_tempdir_list()

    for dir in dirlist:
        if dir != _os.curdir:
            dir = _os.path.normcase(_os.path.abspath(dir))
        # Try only a few names per directory.
        for seq in range(100):
            name = next(namer)
            filename = _os.path.join(dir, name)
            try:
                fd = _os.open(filename, _bin_openflags, 0o600)
                try:
                    try:
                        with _io.open(fd, 'wb', closefd=False) as fp:
                            fp.write(b'blat')
                    finally:
                        _os.close(fd)
                finally:
                    _os.unlink(filename)
                return dir
            except FileExistsError:
                pass
            except OSError:
                break   # no point trying more names in this directory
    raise FileNotFoundError(_errno.ENOENT,
                            "No usable temporary directory found in %s" %
                            dirlist) 
Example #29
Source File: file.py    From gnocchi with Apache License 2.0 5 votes vote down vote up
def _get_splits_unbatched(self, metric, key, aggregation, version=3):
        path = self._build_metric_path_for_split(
            metric, aggregation.method, key, version)
        try:
            with open(path, 'rb') as aggregation_file:
                return aggregation_file.read()
        except IOError as e:
            if e.errno == errno.ENOENT:
                return
            raise 
Example #30
Source File: file.py    From gnocchi with Apache License 2.0 5 votes vote down vote up
def _list_split_keys_unbatched(self, metric, aggregations, version=3):
        keys = collections.defaultdict(set)
        for method, grouped_aggregations in itertools.groupby(
                sorted(aggregations, key=ATTRGETTER_METHOD),
                ATTRGETTER_METHOD):
            try:
                files = os.listdir(
                    self._build_metric_path(metric, method))
            except OSError as e:
                if e.errno == errno.ENOENT:
                    raise storage.MetricDoesNotExist(metric)
                raise
            raw_keys = list(map(
                lambda k: k.split("_"),
                filter(
                    lambda f: self._version_check(f, version),
                    files)))
            if not raw_keys:
                continue
            zipped = list(zip(*raw_keys))
            k_timestamps = utils.to_timestamps(zipped[0])
            k_granularities = list(map(utils.to_timespan, zipped[1]))
            grouped_aggregations = list(grouped_aggregations)
            for timestamp, granularity in six.moves.zip(
                    k_timestamps, k_granularities):
                for agg in grouped_aggregations:
                    if granularity == agg.granularity:
                        keys[agg].add(carbonara.SplitKey(
                            timestamp,
                            sampling=granularity))
                        break
        return keys