Python os.utime() Examples

The following are 30 code examples of os.utime(). 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: run.py    From github-stats with MIT License 6 votes vote down vote up
def check_for_update():
  if os.path.exists(FILE_UPDATE):
    mtime = os.path.getmtime(FILE_UPDATE)
    last = datetime.utcfromtimestamp(mtime).strftime('%Y-%m-%d')
    today = datetime.utcnow().strftime('%Y-%m-%d')
    if last == today:
      return
  try:
    with open(FILE_UPDATE, 'a'):
      os.utime(FILE_UPDATE, None)
    request = urllib2.Request(
      CORE_VERSION_URL,
      urllib.urlencode({'version': __version__}),
    )
    response = urllib2.urlopen(request)
    with open(FILE_UPDATE, 'w') as update_json:
      update_json.write(response.read())
  except (urllib2.HTTPError, urllib2.URLError):
    pass 
Example #2
Source File: shutil.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def copystat(src, dst):
    """Copy file metadata

    Copy the permission bits, last access time, last modification time, and
    flags from `src` to `dst`. On Linux, copystat() also copies the "extended
    attributes" where possible. The file contents, owner, and group are
    unaffected. `src` and `dst` are path names given as strings.
    """
    st = os.stat(src)
    mode = stat.S_IMODE(st.st_mode)
    if hasattr(os, 'utime'):
        os.utime(dst, (st.st_atime, st.st_mtime))
    if hasattr(os, 'chmod'):
        os.chmod(dst, mode)
    if hasattr(os, 'chflags') and hasattr(st, 'st_flags'):
        try:
            os.chflags(dst, st.st_flags)
        except OSError, why:
            for err in 'EOPNOTSUPP', 'ENOTSUP':
                if hasattr(errno, err) and why.errno == getattr(errno, err):
                    break
            else:
                raise 
Example #3
Source File: __init__.py    From python-netsurv with MIT License 6 votes vote down vote up
def touch(self, mode=0o666, exist_ok=True):
        """
        Create this file with the given access mode, if it doesn't exist.
        """
        if self._closed:
            self._raise_closed()
        if exist_ok:
            # First try to bump modification time
            # Implementation note: GNU touch uses the UTIME_NOW option of
            # the utimensat() / futimens() functions.
            try:
                self._accessor.utime(self, None)
            except OSError:
                # Avoid exception chaining
                pass
            else:
                return
        flags = os.O_CREAT | os.O_WRONLY
        if not exist_ok:
            flags |= os.O_EXCL
        fd = self._raw_open(flags, mode)
        os.close(fd) 
Example #4
Source File: __init__.py    From python-netsurv with MIT License 6 votes vote down vote up
def touch(self, mode=0o666, exist_ok=True):
        """
        Create this file with the given access mode, if it doesn't exist.
        """
        if self._closed:
            self._raise_closed()
        if exist_ok:
            # First try to bump modification time
            # Implementation note: GNU touch uses the UTIME_NOW option of
            # the utimensat() / futimens() functions.
            try:
                self._accessor.utime(self, None)
            except OSError:
                # Avoid exception chaining
                pass
            else:
                return
        flags = os.O_CREAT | os.O_WRONLY
        if not exist_ok:
            flags |= os.O_EXCL
        fd = self._raw_open(flags, mode)
        os.close(fd) 
Example #5
Source File: domain_substitution.py    From ungoogled-chromium with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _update_timestamp(path: os.PathLike, set_new: bool) -> None:
    """
    Context manager to set the timestamp of the path to plus or
    minus a fixed delta, regardless of modifications within the context.

    if set_new is True, the delta is added. Otherwise, the delta is subtracted.
    """
    stats = os.stat(path)
    if set_new:
        new_timestamp = (stats.st_atime_ns + _TIMESTAMP_DELTA, stats.st_mtime_ns + _TIMESTAMP_DELTA)
    else:
        new_timestamp = (stats.st_atime_ns - _TIMESTAMP_DELTA, stats.st_mtime_ns - _TIMESTAMP_DELTA)
    try:
        yield
    finally:
        os.utime(path, ns=new_timestamp)


# Public Methods 
Example #6
Source File: ipc.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def update_atime(self):
        """Update the atime of the socket file all few hours.

        From the XDG basedir spec:

        To ensure that your files are not removed, they should have their
        access time timestamp modified at least once every 6 hours of monotonic
        time or the 'sticky' bit should be set on the file.
        """
        path = self._server.fullServerName()
        if not path:
            log.ipc.error("In update_atime with no server path!")
            return

        log.ipc.debug("Touching {}".format(path))

        try:
            os.utime(path)
        except OSError:
            log.ipc.exception("Failed to update IPC socket, trying to "
                              "re-listen...")
            self._server.close()
            self.listen() 
Example #7
Source File: instaloader.py    From instaloader with MIT License 6 votes vote down vote up
def download_pic(self, filename: str, url: str, mtime: datetime,
                     filename_suffix: Optional[str] = None, _attempt: int = 1) -> bool:
        """Downloads and saves picture with given url under given directory with given timestamp.
        Returns true, if file was actually downloaded, i.e. updated."""
        urlmatch = re.search('\\.[a-z0-9]*\\?', url)
        file_extension = url[-3:] if urlmatch is None else urlmatch.group(0)[1:-1]
        if filename_suffix is not None:
            filename += '_' + filename_suffix
        filename += '.' + file_extension
        # A post is considered "commited" if the json file exists and is not malformed.
        if self.commit_mode:
            if self._committed and os.path.isfile(filename):
                self.context.log(filename + ' exists', end=' ', flush=True)
                return False
        else:
            if os.path.isfile(filename):
                self.context.log(filename + ' exists', end=' ', flush=True)
                return False
        self.context.get_and_write_raw(url, filename)
        os.utime(filename, (datetime.now().timestamp(), mtime.timestamp()))
        return True 
Example #8
Source File: bear_export_sync.py    From Bear-Markdown-Export with MIT License 6 votes vote down vote up
def textbundle_to_bear(md_text, md_file, mod_dt):
    md_text = restore_tags(md_text)
    bundle = os.path.split(md_file)[0]
    match = re.search(r'\{BearID:(.+?)\}', md_text)
    if match:
        uuid = match.group(1)
        # Remove old BearID: from new note
        md_text = re.sub(r'\<\!-- ?\{BearID\:' + uuid + r'\} ?--\>', '', md_text).rstrip() + '\n'
        md_text = insert_link_top_note(md_text, 'Images added! Link to original note: ', uuid)
    else:
        # New textbundle (with images), add path as tag: 
        md_text = get_tag_from_path(md_text, bundle, export_path)
    write_file(md_file, md_text, mod_dt)
    os.utime(bundle, (-1, mod_dt))
    subprocess.call(['open', '-a', '/applications/bear.app', bundle])
    time.sleep(0.5) 
Example #9
Source File: obs_operator.py    From openSUSE-release-tools with GNU General Public License v2.0 6 votes vote down vote up
def oscrc_create(self, oscrc_file, apiurl, cookiejar_file, user):
        sentry_dsn = sentry_client().dsn
        sentry_environment = sentry_client().options.get('environment')

        oscrc_file.write('\n'.join([
            '[general]',
            # Passthru sentry_sdk options to allow for reporting on subcommands.
            'sentry_sdk.dsn = {}'.format(sentry_dsn) if sentry_dsn else '',
            'sentry_sdk.environment = {}'.format(sentry_environment) if sentry_environment else '',
            'apiurl = {}'.format(apiurl),
            'cookiejar = {}'.format(cookiejar_file.name),
            'staging.color = 0',
            '[{}]'.format(apiurl),
            'user = {}'.format(user),
            'pass = invalid',
            '',
        ]).encode('utf-8'))
        oscrc_file.flush()

        # In order to avoid osc clearing the cookie file the modified time of
        # the oscrc file must be set further into the past.
        # if int(round(config_mtime)) > int(os.stat(cookie_file).st_mtime):
        recent_past = time.time() - 3600
        os.utime(oscrc_file.name, (recent_past, recent_past)) 
Example #10
Source File: metadata.py    From pi-timolo with MIT License 6 votes vote down vote up
def write(self, preserve_timestamps=False):
        """Write the metadata back to the image.

        Args:
        preserve_timestamps -- whether to preserve the file's original
                               timestamps (access time and modification time)
                               Type: boolean
        """
        self._image._writeMetadata()
        if self.filename is None:
            return

        if preserve_timestamps:
            # Revert to the original timestamps
            os.utime(self.filename, (self._atime, self._mtime))

        else:
            # Reset the reference timestamps
            stat = os.stat(self.filename)
            self._atime = stat.st_atime
            self._mtime = stat.st_mtime 
Example #11
Source File: local.py    From python-netsurv with MIT License 5 votes vote down vote up
def setmtime(self, mtime=None):
        """ set modification time for the given path.  if 'mtime' is None
        (the default) then the file's mtime is set to current time.

        Note that the resolution for 'mtime' is platform dependent.
        """
        if mtime is None:
            return py.error.checked_call(os.utime, self.strpath, mtime)
        try:
            return py.error.checked_call(os.utime, self.strpath, (-1, mtime))
        except py.error.EINVAL:
            return py.error.checked_call(os.utime, self.strpath, (self.atime(), mtime)) 
Example #12
Source File: filetools.py    From NXP-MCUBootFlasher with Apache License 2.0 5 votes vote down vote up
def copystat(src, dst, forceMode=None):
	"""Copy all stat info (mode bits, atime and mtime) from src to dst"""
	st = os.stat(src)
	mode = stat.S_IMODE(st.st_mode)
	if forceMode != None:
		mode = forceMode
	if hasattr(os, 'utime'):
		os.utime(dst, (st.st_atime, st.st_mtime))
	if hasattr(os, 'chmod'):
		os.chmod(dst, mode) 
Example #13
Source File: local.py    From python-netsurv with MIT License 5 votes vote down vote up
def setmtime(self, mtime=None):
        """ set modification time for the given path.  if 'mtime' is None
        (the default) then the file's mtime is set to current time.

        Note that the resolution for 'mtime' is platform dependent.
        """
        if mtime is None:
            return py.error.checked_call(os.utime, self.strpath, mtime)
        try:
            return py.error.checked_call(os.utime, self.strpath, (-1, mtime))
        except py.error.EINVAL:
            return py.error.checked_call(os.utime, self.strpath, (self.atime(), mtime)) 
Example #14
Source File: hooks.py    From py2deb with MIT License 5 votes vote down vote up
def touch(filename):
    """
    The equivalent of the UNIX ``touch`` program in Python.

    :param filename: The absolute pathname of the file to touch (a string).
    """
    with open(filename, 'a'):
        os.utime(filename, None) 
Example #15
Source File: shutil.py    From meddle with MIT License 5 votes vote down vote up
def copystat(src, dst):
    """Copy all stat info (mode bits, atime, mtime, flags) from src to dst"""
    st = os.stat(src)
    mode = stat.S_IMODE(st.st_mode)
    if hasattr(os, 'utime'):
        os.utime(dst, (st.st_atime, st.st_mtime))
    if hasattr(os, 'chmod'):
        os.chmod(dst, mode)
    if hasattr(os, 'chflags') and hasattr(st, 'st_flags'):
        try:
            os.chflags(dst, st.st_flags)
        except OSError, why:
            if (not hasattr(errno, 'EOPNOTSUPP') or
                why.errno != errno.EOPNOTSUPP):
                raise 
Example #16
Source File: bear_export_sync.py    From Bear-Markdown-Export with MIT License 5 votes vote down vote up
def write_file(filename, file_content, modified):
    with open(filename, "w", encoding='utf-8') as f:
        f.write(file_content)
    if modified > 0:
        os.utime(filename, (-1, modified)) 
Example #17
Source File: bear_export_sync.py    From Bear-Markdown-Export with MIT License 5 votes vote down vote up
def make_text_bundle(md_text, filepath, mod_dt):
    '''
    Exports as Textbundles with images included 
    '''
    bundle_path = filepath + '.textbundle'
    assets_path = os.path.join(bundle_path, 'assets')    
    if not os.path.exists(bundle_path):
        os.makedirs(bundle_path)
        os.makedirs(assets_path)
        
    info = '''{
    "transient" : true,
    "type" : "net.daringfireball.markdown",
    "creatorIdentifier" : "net.shinyfrog.bear",
    "version" : 2
    }'''
    matches = re.findall(r'\[image:(.+?)\]', md_text)
    for match in matches:
        image_name = match
        new_name = image_name.replace('/', '_')
        source = os.path.join(bear_image_path, image_name)
        target = os.path.join(assets_path, new_name)
        shutil.copy2(source, target)

    md_text = re.sub(r'\[image:(.+?)/(.+?)\]', r'![](assets/\1_\2)', md_text)
    write_file(bundle_path + '/text.md', md_text, mod_dt)
    write_file(bundle_path + '/info.json', info, mod_dt)
    os.utime(bundle_path, (-1, mod_dt)) 
Example #18
Source File: file_operations.py    From kano-toolset with GNU General Public License v2.0 5 votes vote down vote up
def touch(path, times=None):
    """Set the access and modified times of the file specified by path.

    The function calls :func:`.ensure_dir` beforehand for you.
    This is essentially a simple wrapper for :func:`os.utime`.

    Args:
        path (str): Path to the file create/modify
        times (tuple): See :func:`os.utime`

    Returns:
        bool: Whether the operation was successful or not
    """
    try:
        ensure_dir(os.path.dirname(path))
        with open(path, 'a'):
            os.utime(path, times)

    except (IOError, OSError) as error:
        from kano.logging import logger
        logger.error(
            "Could not touch {} due to permission/IO - {}"
            .format(path, error)
        )
        return False
    return True 
Example #19
Source File: _http.py    From bitmask-dev with GNU General Public License v3.0 5 votes vote down vote up
def _write_to_file(content, path):
    folder = os.path.split(path)[0]
    if not os.path.isdir(folder):
        os.makedirs(folder)
    with open(path, 'w') as f:
        f.write(content)
    # touch it to update its utime
    os.utime(path, None) 
Example #20
Source File: files.py    From fac with MIT License 5 votes vote down vote up
def utime(self, *args, **kwargs):
        os.utime(self.file, *args, **kwargs) 
Example #21
Source File: logical.py    From pyaff4 with Apache License 2.0 5 votes vote down vote up
def resetTimestampsPosix(destFile, lastWritten, lastAccessed, recordChanged, birthTime):
    if lastWritten == None or lastAccessed == None:
        return
    try:
        lw = parse(lastWritten.value)
        la = parse(lastAccessed.value)
        os.utime(destFile, ((la - epoch).total_seconds(), (lw - epoch).total_seconds()))
    except Exception:
        traceback.print_exc()

# default implementation does nothing at present on non posix environments 
Example #22
Source File: local.py    From filesystem_spec with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def touch(self, path, **kwargs):
        path = self._strip_protocol(path)
        if self.auto_mkdir:
            self.makedirs(self._parent(path), exist_ok=True)
        if self.exists(path):
            os.utime(path, None)
        else:
            open(path, "a").close() 
Example #23
Source File: tarfile.py    From jbox with MIT License 5 votes vote down vote up
def utime(self, tarinfo, targetpath):
        """Set modification time of targetpath according to tarinfo.
        """
        if not hasattr(os, 'utime'):
            return
        try:
            os.utime(targetpath, (tarinfo.mtime, tarinfo.mtime))
        except EnvironmentError as e:
            raise ExtractError("could not change modification time")

    #-------------------------------------------------------------------------- 
Example #24
Source File: tarfile.py    From jbox with MIT License 5 votes vote down vote up
def extractall(self, path=".", members=None):
        """Extract all members from the archive to the current working
           directory and set owner, modification time and permissions on
           directories afterwards. `path' specifies a different directory
           to extract to. `members' is optional and must be a subset of the
           list returned by getmembers().
        """
        directories = []

        if members is None:
            members = self

        for tarinfo in members:
            if tarinfo.isdir():
                # Extract directories with a safe mode.
                directories.append(tarinfo)
                tarinfo = copy.copy(tarinfo)
                tarinfo.mode = 0o700
            # Do not set_attrs directories, as we will do that further down
            self.extract(tarinfo, path, set_attrs=not tarinfo.isdir())

        # Reverse sort directories.
        directories.sort(key=lambda a: a.name)
        directories.reverse()

        # Set correct owner, mtime and filemode on directories.
        for tarinfo in directories:
            dirpath = os.path.join(path, tarinfo.name)
            try:
                self.chown(tarinfo, dirpath)
                self.utime(tarinfo, dirpath)
                self.chmod(tarinfo, dirpath)
            except ExtractError as e:
                if self.errorlevel > 1:
                    raise
                else:
                    self._dbg(1, "tarfile: %s" % e) 
Example #25
Source File: shutil.py    From jbox with MIT License 5 votes vote down vote up
def copystat(src, dst):
    """Copy all stat info (mode bits, atime, mtime, flags) from src to dst"""
    st = os.stat(src)
    mode = stat.S_IMODE(st.st_mode)
    if hasattr(os, 'utime'):
        os.utime(dst, (st.st_atime, st.st_mtime))
    if hasattr(os, 'chmod'):
        os.chmod(dst, mode)
    if hasattr(os, 'chflags') and hasattr(st, 'st_flags'):
        try:
            os.chflags(dst, st.st_flags)
        except OSError as why:
            if (not hasattr(errno, 'EOPNOTSUPP') or
                why.errno != errno.EOPNOTSUPP):
                raise 
Example #26
Source File: setup.py    From qgrid with Apache License 2.0 5 votes vote down vote up
def run(self):
        has_npm = self.has_npm()
        if not has_npm:
            log.error("`npm` unavailable.  If you're running this command using sudo, make sure `npm` is available to sudo")

        env = os.environ.copy()
        env['PATH'] = npm_path

        if self.should_run_npm_install():
            log.info("Installing build dependencies with npm.  This may take a while...")
            check_call(['npm', 'install'], cwd=node_root, stdout=sys.stdout, stderr=sys.stderr)
            os.utime(self.node_modules, None)

        for t in self.targets:
            if not exists(t):
                msg = 'Missing file: %s' % t
                if not has_npm:
                    msg += '\nnpm is required to build a development version of a widget extension'
                raise ValueError(msg)

        # update package data in case this created new files
        update_package_data(self.distribution) 
Example #27
Source File: conditional_downloads.py    From bitmask-dev with GNU General Public License v3.0 5 votes vote down vote up
def main(reactor, *args):
    client = http.HTTPClient()
    fname = os.path.join(tmp, str(uuid.uuid4()))
    yield httpRequest(client._agent, URI, method='GET', saveto=fname)
    filesize = os.path.getsize(fname)
    assert filesize > 1
    # touch file to 5 minutes in the past
    past = int(os.path.getmtime(fname)) - 300
    print "PAST MTIME", past
    os.utime(fname, (past, past))
    assert os.path.getmtime(fname) == past
    yield httpRequest(client._agent, URI, method='GET', saveto=fname)
    # it was not modified
    current = os.path.getmtime(fname)
    print "CURRENT MTIME", current
    assert int(current) == past
    print 'OK'
    shutil.rmtree(tmp) 
Example #28
Source File: test_states.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_4_Autoreload(self):
        # If test_3 has not been executed, the server won't be stopped,
        # so we'll have to do it.
        if engine.state != engine.states.EXITING:
            engine.exit()

        # Start the demo script in a new process
        p = helper.CPProcess(ssl=(self.scheme.lower() == 'https'))
        p.write_conf(extra='test_case_name: "test_4_Autoreload"')
        p.start(imports='cherrypy.test._test_states_demo')
        try:
            self.getPage('/start')
            start = float(self.body)

            # Give the autoreloader time to cache the file time.
            time.sleep(2)

            # Touch the file
            os.utime(os.path.join(thisdir, '_test_states_demo.py'), None)

            # Give the autoreloader time to re-exec the process
            time.sleep(2)
            host = cherrypy.server.socket_host
            port = cherrypy.server.socket_port
            portend.occupied(host, port, timeout=5)

            self.getPage('/start')
            if not (float(self.body) > start):
                raise AssertionError('start time %s not greater than %s' %
                                     (float(self.body), start))
        finally:
            # Shut down the spawned process
            self.getPage('/exit')
        p.join() 
Example #29
Source File: util.py    From apio with GNU General Public License v2.0 5 votes vote down vote up
def change_filemtime(path, time):
    os.utime(path, (time, time)) 
Example #30
Source File: config.py    From bitmask-dev with GNU General Public License v3.0 5 votes vote down vote up
def update_modification_ts(path):
    """
    Sets modification time of a file to current time.

    :param path: the path to set ts to.
    :type path: str
    :returns: modification time
    :rtype: datetime object
    """
    os.utime(path, None)
    return get_mtime(path)