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: setup.py    From qgrid with Apache License 2.0 6 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 #2
Source File: conditional_downloads.py    From bitmask-dev with GNU General Public License v3.0 6 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 #3
Source File: test_smbclient_shutil.py    From smbprotocol with MIT License 6 votes vote down vote up
def test_copy2_with_dir_as_target(smb_share):
    src_filename = "%s\\source.txt" % smb_share
    dst_filename = "%s\\directory" % smb_share
    mkdir(dst_filename)

    with open_file(src_filename, mode='w') as fd:
        fd.write(u"content")
    utime(src_filename, times=(1024, 1024))

    actual = copy2(src_filename, dst_filename)
    assert actual == ntpath.join(dst_filename, "source.txt")

    with open_file("%s\\source.txt" % dst_filename) as fd:
        assert fd.read() == u"content"

    src_stat = smbclient_stat(src_filename)

    actual = smbclient_stat("%s\\source.txt" % dst_filename)
    assert actual.st_atime == 1024
    assert actual.st_mtime == 1024
    assert actual.st_ctime != src_stat.st_ctime
    assert actual.st_chgtime != src_stat.st_chgtime
    assert actual.st_file_attributes & FileAttributes.FILE_ATTRIBUTE_READONLY == 0 
Example #4
Source File: test_smbclient_shutil.py    From smbprotocol with MIT License 6 votes vote down vote up
def test_copystat_local_to_local(tmpdir):
    test_dir = tmpdir.mkdir("test")
    src_filename = "%s\\source.txt" % test_dir
    dst_filename = "%s\\target.txt" % test_dir

    with open(src_filename, mode='w') as fd:
        fd.write(u"content")
    os.chmod(src_filename, stat.S_IREAD)
    os.utime(src_filename, (1024, 1024))

    with open(dst_filename, mode='w') as fd:
        fd.write(u"content")

    copystat(src_filename, dst_filename)

    actual = os.stat(dst_filename)
    assert actual.st_atime == 1024
    assert actual.st_mtime == 1024
    assert stat.S_IMODE(actual.st_mode) & stat.S_IWRITE == 0 
Example #5
Source File: test_smbclient_shutil.py    From smbprotocol with MIT License 6 votes vote down vote up
def test_copystat_remote_to_local(smb_share, tmpdir):
    test_dir = tmpdir.mkdir("test")
    src_filename = "%s\\source.txt" % smb_share
    dst_filename = "%s\\target.txt" % test_dir

    with open_file(src_filename, mode='w', file_attributes=FileAttributes.FILE_ATTRIBUTE_READONLY) as fd:
        fd.write(u"content")
    utime(src_filename, times=(1024, 1024))

    with open(dst_filename, mode='w') as fd:
        fd.write(u"content")

    copystat(src_filename, dst_filename)

    actual = os.stat(dst_filename)
    assert actual.st_atime == 1024
    assert actual.st_mtime == 1024
    assert stat.S_IMODE(actual.st_mode) & stat.S_IWRITE == 0 
Example #6
Source File: t2t_decoder.py    From fine-lm with MIT License 6 votes vote down vote up
def decode(estimator, hparams, decode_hp):
  """Decode from estimator. Interactive, from file, or from dataset."""
  if FLAGS.decode_interactive:
    if estimator.config.use_tpu:
      raise ValueError("TPU can only decode from dataset.")
    decoding.decode_interactively(estimator, hparams, decode_hp,
                                  checkpoint_path=FLAGS.checkpoint_path)
  elif FLAGS.decode_from_file:
    if estimator.config.use_tpu:
      raise ValueError("TPU can only decode from dataset.")
    decoding.decode_from_file(estimator, FLAGS.decode_from_file, hparams,
                              decode_hp, FLAGS.decode_to_file,
                              checkpoint_path=FLAGS.checkpoint_path)
    if FLAGS.checkpoint_path and FLAGS.keep_timestamp:
      ckpt_time = os.path.getmtime(FLAGS.checkpoint_path + ".index")
      os.utime(FLAGS.decode_to_file, (ckpt_time, ckpt_time))
  else:
    decoding.decode_from_dataset(
        estimator,
        FLAGS.problem,
        hparams,
        decode_hp,
        decode_to_file=FLAGS.decode_to_file,
        dataset_split="test" if FLAGS.eval_use_test_set else None) 
Example #7
Source File: test_smbclient_shutil.py    From smbprotocol with MIT License 6 votes vote down vote up
def test_copy2(smb_share):
    src_filename = "%s\\source.txt" % smb_share
    dst_filename = "%s\\target.txt" % smb_share

    with open_file(src_filename, mode='w', file_attributes=FileAttributes.FILE_ATTRIBUTE_READONLY) as fd:
        fd.write(u"content")
    utime(src_filename, times=(1024, 1024))

    actual = copy2(src_filename, dst_filename)
    assert actual == dst_filename

    with open_file(dst_filename) as fd:
        assert fd.read() == u"content"

    src_stat = smbclient_stat(src_filename)

    actual = smbclient_stat(dst_filename)
    assert actual.st_atime == 1024
    assert actual.st_mtime == 1024
    assert actual.st_ctime != src_stat.st_ctime
    assert actual.st_chgtime != src_stat.st_chgtime
    assert actual.st_file_attributes & FileAttributes.FILE_ATTRIBUTE_READONLY == FileAttributes.FILE_ATTRIBUTE_READONLY 
Example #8
Source File: test_smbclient_shutil.py    From smbprotocol with MIT License 6 votes vote down vote up
def test_copystat_of_file(smb_share):
    src_filename = "%s\\source.txt" % smb_share
    dst_filename = "%s\\target.txt" % smb_share

    with open_file(src_filename, mode='w', file_attributes=FileAttributes.FILE_ATTRIBUTE_READONLY) as fd:
        fd.write(u"content")
    utime(src_filename, (1024, 1024))

    with open_file(dst_filename, mode='w') as fd:
        fd.write(u"content")

    copystat(src_filename, dst_filename)

    actual = smbclient_stat(dst_filename)
    assert actual.st_atime == 1024
    assert actual.st_mtime == 1024
    assert actual.st_file_attributes & FileAttributes.FILE_ATTRIBUTE_READONLY == FileAttributes.FILE_ATTRIBUTE_READONLY 
Example #9
Source File: test_smbclient_shutil.py    From smbprotocol with MIT License 6 votes vote down vote up
def test_copystat_of_dir(smb_share):
    src_dirname = "%s\\source" % smb_share
    dst_dirname = "%s\\target" % smb_share

    with open_file(src_dirname, mode='xb', file_type='dir', file_attributes=FileAttributes.FILE_ATTRIBUTE_READONLY,
                   buffering=0):
        pass
    utime(src_dirname, (-1024, -1024))  # Test out dates earlier than EPOCH.

    mkdir(dst_dirname)

    copystat(src_dirname, dst_dirname)

    actual = smbclient_stat(dst_dirname)
    assert actual.st_atime == -1024
    assert actual.st_mtime == -1024
    assert actual.st_file_attributes & FileAttributes.FILE_ATTRIBUTE_READONLY == FileAttributes.FILE_ATTRIBUTE_READONLY 
Example #10
Source File: CacheDir.py    From arnold-usd with Apache License 2.0 6 votes vote down vote up
def CacheRetrieveFunc(target, source, env):
    t = target[0]
    fs = t.fs
    cd = env.get_CacheDir()
    cachedir, cachefile = cd.cachepath(t)
    if not fs.exists(cachefile):
        cd.CacheDebug('CacheRetrieve(%s):  %s not in cache\n', t, cachefile)
        return 1
    cd.CacheDebug('CacheRetrieve(%s):  retrieving from %s\n', t, cachefile)
    if SCons.Action.execute_actions:
        if fs.islink(cachefile):
            fs.symlink(fs.readlink(cachefile), t.get_internal_path())
        else:
            env.copy_from_cache(cachefile, t.get_internal_path())
            try:
                os.utime(cachefile, None)
            except OSError:
                pass
        st = fs.stat(cachefile)
        fs.chmod(t.get_internal_path(), stat.S_IMODE(st[stat.ST_MODE]) | stat.S_IWRITE)
    return 0 
Example #11
Source File: mailbox.py    From meddle with MIT License 6 votes vote down vote up
def __setitem__(self, key, message):
        """Replace the keyed message; raise KeyError if it doesn't exist."""
        old_subpath = self._lookup(key)
        temp_key = self.add(message)
        temp_subpath = self._lookup(temp_key)
        if isinstance(message, MaildirMessage):
            # temp's subdir and suffix were specified by message.
            dominant_subpath = temp_subpath
        else:
            # temp's subdir and suffix were defaults from add().
            dominant_subpath = old_subpath
        subdir = os.path.dirname(dominant_subpath)
        if self.colon in dominant_subpath:
            suffix = self.colon + dominant_subpath.split(self.colon)[-1]
        else:
            suffix = ''
        self.discard(key)
        new_path = os.path.join(self._path, subdir, key + suffix)
        os.rename(os.path.join(self._path, temp_subpath), new_path)
        if isinstance(message, MaildirMessage):
            os.utime(new_path, (os.path.getatime(new_path),
                                message.get_date())) 
Example #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
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 #22
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 #23
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 #24
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 #25
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 #26
Source File: win32.py    From arnold-usd with Apache License 2.0 5 votes vote down vote up
def win_api_copyfile(src,dst):
            CopyFile(src,dst)
            os.utime(dst) 
Example #27
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 #28
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 #29
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 #30
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