Python os.utime() Examples

The following are 30 code examples for showing how to use os.utime(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module os , or try the search function .

Example 1
Project: smbprotocol   Author: jborean93   File: test_smbclient_shutil.py    License: 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 2
Project: smbprotocol   Author: jborean93   File: test_smbclient_shutil.py    License: 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 3
Project: smbprotocol   Author: jborean93   File: test_smbclient_shutil.py    License: 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 4
Project: smbprotocol   Author: jborean93   File: test_smbclient_shutil.py    License: 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 5
Project: smbprotocol   Author: jborean93   File: test_smbclient_shutil.py    License: 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
Project: smbprotocol   Author: jborean93   File: test_smbclient_shutil.py    License: 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 7
Project: fine-lm   Author: akzaidi   File: t2t_decoder.py    License: 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 8
Project: qutebrowser   Author: qutebrowser   File: ipc.py    License: 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 9
Project: instaloader   Author: instaloader   File: instaloader.py    License: 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 10
Project: openSUSE-release-tools   Author: openSUSE   File: obs_operator.py    License: 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 11
Project: github-stats   Author: lipis   File: run.py    License: 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 12
Project: pi-timolo   Author: pageauc   File: metadata.py    License: 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 13
Project: qgrid   Author: quantopian   File: setup.py    License: 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 14
Project: Bear-Markdown-Export   Author: markgrovs   File: bear_export_sync.py    License: 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 15
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 16
Project: python-netsurv   Author: sofia-netsurv   File: __init__.py    License: 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 17
Project: python-netsurv   Author: sofia-netsurv   File: __init__.py    License: 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 18
Project: meddle   Author: glmcdona   File: mailbox.py    License: 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 19
Project: arnold-usd   Author: Autodesk   File: CacheDir.py    License: 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 20
Project: bitmask-dev   Author: leapcode   File: conditional_downloads.py    License: 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 21
Project: ironpython2   Author: IronLanguages   File: shutil.py    License: 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 22
Project: cherrypy   Author: cherrypy   File: test_states.py    License: 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 23
Project: smbprotocol   Author: jborean93   File: shutil.py    License: MIT License 5 votes vote down vote up
def copystat(src, dst, follow_symlinks=True, **kwargs):
    """
    Copy the read only attribute, last access time, and last modification time from src to dst. The file contents,
    owner, and group are unaffected.

    If follow_symlinks is 'False' and src and dst both refer to symbolic links, copystat() will operate on the
    symbolic links themselves rather than the files the symbolic links refer to.

    :param src: The src file or directory to copy the read only flag from.
    :param dst: The dst file or directory to copy the read only flag to.
    :param follow_symlinks: Whether to copy the read only flag on the symlink or the target of the symlink.
    :param kwargs: Common arguments used to build the SMB Session for any UNC paths.
    """
    src_stat = _get_file_stat(src, follow_symlinks, **kwargs)
    src_mode = stat.S_IMODE(src_stat.st_mode)

    # *_ns was only added in Python 3, fallback to a manual calculation from seconds since EPOCH.
    atime_ns = getattr(src_stat, 'st_atime_ns', src_stat.st_atime * 1000000000)
    mtime_ns = getattr(src_stat, 'st_mtime_ns', src_stat.st_mtime * 1000000000)

    norm_dst = ntpath.normpath(dst)
    if norm_dst.startswith('\\\\'):
        read_only = not (src_mode & stat.S_IWRITE == stat.S_IWRITE and src_mode & stat.S_IREAD == stat.S_IREAD)
        _set_file_basic_info(dst, follow_symlinks, read_only=read_only, atime_ns=atime_ns, mtime_ns=mtime_ns, **kwargs)
    else:
        if not follow_symlinks and sys.version_info[0] < 3:
            # Python 2 always follows symlinks and does not have a kwarg to override, we can only just fail here.
            raise NotImplementedError("utime: follow_symlinks unavailable on this platform")

        _local_chmod(dst, src_mode, follow_symlinks)

        if sys.version_info[0] < 3:
            os.utime(dst, (atime_ns / 1000000000, mtime_ns / 1000000000))
        else:
            os.utime(dst, ns=(atime_ns, mtime_ns), follow_symlinks=follow_symlinks) 
Example 24
Project: smbprotocol   Author: jborean93   File: test_smbclient_shutil.py    License: MIT License 5 votes vote down vote up
def test_copystat_local_to_local_symlink_follow(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")

    src_link = "%s\\source-link.txt" % test_dir
    dst_link = "%s\\target-link.txt" % test_dir

    os.symlink(src_filename, src_link)
    os.symlink(dst_filename, dst_link)

    copystat(src_link, dst_link)

    actual_file = os.stat(dst_filename)
    assert actual_file.st_atime == 1024
    assert actual_file.st_mtime == 1024
    assert stat.S_IMODE(actual_file.st_mode) & stat.S_IWRITE == 0

    actual_link = os.lstat(dst_link)
    assert actual_link.st_atime != 1024
    assert actual_link.st_mtime != 1024
    assert stat.S_IMODE(actual_link.st_mode) & stat.S_IWRITE == stat.S_IWRITE 
Example 25
Project: smbprotocol   Author: jborean93   File: test_smbclient_shutil.py    License: MIT License 5 votes vote down vote up
def test_copystat_symlink_follow(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))

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

    src_link = "%s\\source-link.txt" % smb_share
    dst_link = "%s\\target-link.txt" % smb_share

    symlink(src_filename, src_link)
    symlink(dst_filename, dst_link)

    copystat(src_link, dst_link)

    actual_file = smbclient_stat(dst_link)
    assert actual_file.st_atime == 1024
    assert actual_file.st_mtime == 1024
    assert actual_file.st_file_attributes & FileAttributes.FILE_ATTRIBUTE_READONLY == \
        FileAttributes.FILE_ATTRIBUTE_READONLY

    actual_link = smbclient_stat(dst_link, follow_symlinks=False)
    assert actual_link.st_atime != 1024
    assert actual_link.st_mtime != 1024
    assert actual_link.st_file_attributes & FileAttributes.FILE_ATTRIBUTE_READONLY == 0 
Example 26
Project: smbprotocol   Author: jborean93   File: test_smbclient_shutil.py    License: MIT License 5 votes vote down vote up
def test_copystat_symlink_dont_follow(smb_share):
    src_filename = "%s\\source.txt" % smb_share
    dst_filename = "%s\\target.txt" % smb_share

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

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

    src_link = "%s\\source-link.txt" % smb_share
    dst_link = "%s\\target-link.txt" % smb_share

    symlink(src_filename, src_link)
    symlink(dst_filename, dst_link)

    _set_file_attributes(src_link, FileAttributes.FILE_ATTRIBUTE_READONLY)
    utime(src_link, times=(1024, 1024), follow_symlinks=False)

    copystat(src_link, dst_link, follow_symlinks=False)

    actual_file = smbclient_stat(dst_link)
    assert actual_file.st_atime != 1024
    assert actual_file.st_mtime != 1024
    assert actual_file.st_file_attributes & FileAttributes.FILE_ATTRIBUTE_READONLY == 0

    actual_link = smbclient_stat(dst_link, follow_symlinks=False)
    assert actual_link.st_atime == 1024
    assert actual_link.st_mtime == 1024
    assert actual_link.st_file_attributes & FileAttributes.FILE_ATTRIBUTE_READONLY == \
        FileAttributes.FILE_ATTRIBUTE_READONLY 
Example 27
Project: jawfish   Author: war-and-code   File: tarfile.py    License: 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 28
Project: jawfish   Author: war-and-code   File: tarfile.py    License: 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
Project: qtsass   Author: spyder-ide   File: __init__.py    License: MIT License 5 votes vote down vote up
def touch(file):
    """Touch a file."""

    with open(str(file), 'a'):
        os.utime(str(file), None) 
Example 30
Project: daily-wallpaper   Author: atareao   File: config.py    License: MIT License 5 votes vote down vote up
def check(self):
        if not os.path.exists(CONFIG_FILE):
            if not os.path.exists(CONFIG_APP_DIR):
                os.makedirs(CONFIG_APP_DIR, 0o700)
            with open(CONFIG_FILE, 'a'):
                os.utime(CONFIG_FILE, None)
            os.chmod(CONFIG_FILE, 0o600)