Python shutil.SameFileError() Examples

The following are 22 code examples of shutil.SameFileError(). 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 shutil , or try the search function .
Example #1
Source File: test_shutil.py    From ironpython3 with Apache License 2.0 7 votes vote down vote up
def test_dont_copy_file_onto_symlink_to_itself(self):
        # bug 851123.
        os.mkdir(TESTFN)
        src = os.path.join(TESTFN, 'cheese')
        dst = os.path.join(TESTFN, 'shop')
        try:
            with open(src, 'w') as f:
                f.write('cheddar')
            # Using `src` here would mean we end up with a symlink pointing
            # to TESTFN/TESTFN/cheese, while it should point at
            # TESTFN/cheese.
            os.symlink('cheese', dst)
            self.assertRaises(shutil.SameFileError, shutil.copyfile, src, dst)
            with open(src, 'r') as f:
                self.assertEqual(f.read(), 'cheddar')
            os.remove(dst)
        finally:
            shutil.rmtree(TESTFN, ignore_errors=True) 
Example #2
Source File: test_shutil.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_dont_copy_file_onto_symlink_to_itself(self):
        # bug 851123.
        os.mkdir(TESTFN)
        src = os.path.join(TESTFN, 'cheese')
        dst = os.path.join(TESTFN, 'shop')
        try:
            with open(src, 'w') as f:
                f.write('cheddar')
            # Using `src` here would mean we end up with a symlink pointing
            # to TESTFN/TESTFN/cheese, while it should point at
            # TESTFN/cheese.
            os.symlink('cheese', dst)
            self.assertRaises(shutil.SameFileError, shutil.copyfile, src, dst)
            with open(src, 'r') as f:
                self.assertEqual(f.read(), 'cheddar')
            os.remove(dst)
        finally:
            shutil.rmtree(TESTFN, ignore_errors=True) 
Example #3
Source File: test_shutil.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_dont_copy_file_onto_symlink_to_itself(self):
        # bug 851123.
        os.mkdir(TESTFN)
        src = os.path.join(TESTFN, 'cheese')
        dst = os.path.join(TESTFN, 'shop')
        try:
            with open(src, 'w') as f:
                f.write('cheddar')
            # Using `src` here would mean we end up with a symlink pointing
            # to TESTFN/TESTFN/cheese, while it should point at
            # TESTFN/cheese.
            os.symlink('cheese', dst)
            self.assertRaises(shutil.SameFileError, shutil.copyfile, src, dst)
            with open(src, 'r') as f:
                self.assertEqual(f.read(), 'cheddar')
            os.remove(dst)
        finally:
            shutil.rmtree(TESTFN, ignore_errors=True) 
Example #4
Source File: config.py    From delta with Apache License 2.0 6 votes vote down vote up
def copy_config(config_path, config):
  ''' copy config file to ckpt dirctory '''
  if isinstance(config_path, Path):
    config_path = str(config_path)
  config_name = os.path.basename(config_path)
  save_config_path = os.path.join(config["solver"]["saver"]["model_path"],
                                  config_name)
  logging.info("Saving config file to {}".format(save_config_path))
  try:
    copyfile(config_path, save_config_path)
  except SameFileError:
    pass

  with open(config_path, 'r') as f:
    logging.info("Config:")
    logging.info(f.read())
  return config 
Example #5
Source File: operations.py    From webfont-generator with MIT License 6 votes vote down vote up
def _copy_file(input_path, output_path):
    ensure_file_directory_exists(output_path)
    try:
        shutil.copyfile(input_path, output_path)
    except shutil.SameFileError as e:
        pass 
Example #6
Source File: requirements_override.py    From fairlearn with MIT License 6 votes vote down vote up
def main(argv):
    parser = build_argument_parser()
    args = parser.parse_args(argv)

    # extract minor version, e.g. '3.6'
    py_version = ".".join(platform.python_version().split(".")[:2])

    # override only if a requirements file for the specific version exists
    version_specific_requirements_file_path = "requirements-{}.txt".format(py_version)
    if os.path.exists(version_specific_requirements_file_path):
        input_file = version_specific_requirements_file_path
    else:
        input_file = 'requirements.txt'

    with _LogWrapper("Overriding {} with {}"
                     .format(args.output, input_file)):
        try:
            shutil.copyfile(input_file, args.output)
        except shutil.SameFileError:
            # destination is already identical with origin
            pass 
Example #7
Source File: test_shutil.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_copyfile(self):
        from_filename = os.path.join(self.test_dir, "test_copyfile_from")
        with open(from_filename, "wb") as f: f.write(self.test_data)

        with self.assertRaises(shutil.SameFileError):
            shutil.copyfile(from_filename, from_filename)

        to_filename = os.path.join(self.test_dir, "test_copyfile_to")
        shutil.copyfile(from_filename, to_filename)
        with open(to_filename, "rb") as f:
            self.assertEqual(f.read(), self.test_data)

        # make sure we can overwrite an existing file
        with open(to_filename, "wb") as f:
            f.write(self.test_data * 2)
        shutil.copyfile(from_filename, to_filename)
        with open(to_filename, "rb") as f:
            self.assertEqual(f.read(), self.test_data) 
Example #8
Source File: sct_utils.py    From spinalcordtoolbox with MIT License 6 votes vote down vote up
def copy(src, dst, verbose=1):
    """Copy src to dst, almost like shutil.copy
    If src and dst are the same files, don't crash.
    """
    if not os.path.isfile(src):
        folder = os.path.dirname(src)
        contents = os.listdir(folder)
        raise Exception("Couldn't find %s in %s (contents: %s)" \
         % (os.path.basename(src), folder, contents))
    try:
        printv("cp %s %s" % (src, dst), verbose=verbose, type="code")
        shutil.copy(src, dst)
    except Exception as e:
        if sys.hexversion < 0x03000000:
            if isinstance(e, shutil.Error) and "same file" in str(e):
                return
        else:
            if isinstance(e, shutil.SameFileError):
                return
        raise # Must be another error 
Example #9
Source File: gacos.py    From kite with GNU General Public License v3.0 5 votes vote down vote up
def save(self, dirname):
        for grd_file in self.config.grd_filenames:
            self._log.info('copying GACOS grid %s', grd_file)
            grd_file = op.join(op.dirname(self.scene.meta.filename), grd_file)
            try:
                shutil.copy(grd_file, dirname)
                shutil.copy(grd_file + '.rsc', dirname)
            except shutil.SameFileError:
                pass

        self.config.grd_filenames = [
            './%s' % op.basename(grd_file)
            for grd_file in self.config.grd_filenames] 
Example #10
Source File: main_win.py    From BlindWatermark with GNU General Public License v3.0 5 votes vote down vote up
def on_pushButton_4_clicked(self):
        """
        将图片复制到工作目录
        """
        work_path = self.my_bwm_parameter.get('work_path',None)
        if not work_path:
            QMessageBox.warning(self,"警告",'未设定工作目录',QMessageBox.Ok)
        else:
            string = 'Done!\n'
            ori_img_path = self.my_bwm_parameter.get('ori_img',False)
            if bool(ori_img_path) and os.path.isfile(ori_img_path):
                img_type = os.path.splitext(ori_img_path)[-1]
                try:
                    shutil.copyfile(ori_img_path,work_path+'ori'+img_type)
                    string+=(ori_img_path+' → '+work_path+'ori'+img_type+'\n')
                except shutil.SameFileError:
                    string+='原图片已存在于工作目录\n'
            wm_path = self.my_bwm_parameter.get('wm',False)
            if bool(wm_path) and os.path.isfile(wm_path):
                img_type = os.path.splitext(wm_path)[-1]
                try:
                    shutil.copyfile(wm_path,work_path+'wm'+img_type)
                    string+=(wm_path+' → '+work_path+'wm'+img_type+'\n')
                except shutil.SameFileError:
                    string+='水印图片已存在于工作目录\n'
            QMessageBox.information(self,'信息',string,QMessageBox.Ok) 
Example #11
Source File: test_shutil.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_module_all_attribute(self):
        self.assertTrue(hasattr(shutil, '__all__'))
        target_api = ['copyfileobj', 'copyfile', 'copymode', 'copystat',
                      'copy', 'copy2', 'copytree', 'move', 'rmtree', 'Error',
                      'SpecialFileError', 'ExecError', 'make_archive',
                      'get_archive_formats', 'register_archive_format',
                      'unregister_archive_format', 'get_unpack_formats',
                      'register_unpack_format', 'unregister_unpack_format',
                      'unpack_archive', 'ignore_patterns', 'chown', 'which',
                      'get_terminal_size', 'SameFileError']
        if hasattr(os, 'statvfs') or os.name == 'nt':
            target_api.append('disk_usage')
        self.assertEqual(set(shutil.__all__), set(target_api)) 
Example #12
Source File: test_shutil.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_copyfile_same_file(self):
        # copyfile() should raise SameFileError if the source and destination
        # are the same.
        src_dir = self.mkdtemp()
        src_file = os.path.join(src_dir, 'foo')
        write_file(src_file, 'foo')
        self.assertRaises(SameFileError, shutil.copyfile, src_file, src_file)
        # But Error should work too, to stay backward compatible.
        self.assertRaises(Error, shutil.copyfile, src_file, src_file) 
Example #13
Source File: test_shutil.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_dont_copy_file_onto_link_to_itself(self):
        # bug 851123.
        os.mkdir(TESTFN)
        src = os.path.join(TESTFN, 'cheese')
        dst = os.path.join(TESTFN, 'shop')
        try:
            with open(src, 'w') as f:
                f.write('cheddar')
            os.link(src, dst)
            self.assertRaises(shutil.SameFileError, shutil.copyfile, src, dst)
            with open(src, 'r') as f:
                self.assertEqual(f.read(), 'cheddar')
            os.remove(dst)
        finally:
            shutil.rmtree(TESTFN, ignore_errors=True) 
Example #14
Source File: test_shutil.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_copyfile_same_file(self):
        # copyfile() should raise SameFileError if the source and destination
        # are the same.
        src_dir = self.mkdtemp()
        src_file = os.path.join(src_dir, 'foo')
        write_file(src_file, 'foo')
        self.assertRaises(SameFileError, shutil.copyfile, src_file, src_file)
        # But Error should work too, to stay backward compatible.
        self.assertRaises(Error, shutil.copyfile, src_file, src_file) 
Example #15
Source File: test_shutil.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_dont_copy_file_onto_link_to_itself(self):
        # bug 851123.
        os.mkdir(TESTFN)
        src = os.path.join(TESTFN, 'cheese')
        dst = os.path.join(TESTFN, 'shop')
        try:
            with open(src, 'w') as f:
                f.write('cheddar')
            os.link(src, dst)
            self.assertRaises(shutil.SameFileError, shutil.copyfile, src, dst)
            with open(src, 'r') as f:
                self.assertEqual(f.read(), 'cheddar')
            os.remove(dst)
        finally:
            shutil.rmtree(TESTFN, ignore_errors=True) 
Example #16
Source File: test_shutil.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_copyfile_same_file(self):
        # copyfile() should raise SameFileError if the source and destination
        # are the same.
        src_dir = self.mkdtemp()
        src_file = os.path.join(src_dir, 'foo')
        write_file(src_file, 'foo')
        self.assertRaises(SameFileError, shutil.copyfile, src_file, src_file)
        # But Error should work too, to stay backward compatible.
        self.assertRaises(Error, shutil.copyfile, src_file, src_file) 
Example #17
Source File: test_shutil.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_dont_copy_file_onto_link_to_itself(self):
        # bug 851123.
        os.mkdir(TESTFN)
        src = os.path.join(TESTFN, 'cheese')
        dst = os.path.join(TESTFN, 'shop')
        try:
            with open(src, 'w') as f:
                f.write('cheddar')
            os.link(src, dst)
            self.assertRaises(shutil.SameFileError, shutil.copyfile, src, dst)
            with open(src, 'r') as f:
                self.assertEqual(f.read(), 'cheddar')
            os.remove(dst)
        finally:
            shutil.rmtree(TESTFN, ignore_errors=True) 
Example #18
Source File: dataio.py    From tridesclous with MIT License 5 votes vote down vote up
def set_probe_file(self, src_probe_filename):
        """
        Set the probe file.
        The probe file is copied inside the working dir.
        
        """
        self._rm_old_probe_file()
        probe_filename = os.path.join(self.dirname, os.path.basename(src_probe_filename))
        try:
            shutil.copyfile(src_probe_filename, probe_filename)
        except shutil.SameFileError:
            # print('probe allready in dir')
            pass
        fix_prb_file_py2(probe_filename)
        # check that the geometry is 2D
        with open(probe_filename) as f:
            d = {}
            exec(f.read(), None, d)
            channel_groups = d['channel_groups']
            for chan_grp, channel_group in channel_groups.items():
                geometry = channel_group.get('geometry', None)
                if geometry is not None:
                    for c, v in geometry.items():
                        assert len(v) == 2, 'Tridesclous need 2D geometry'
                    
                
        
        self.info['probe_filename'] = os.path.basename(probe_filename)
        self.flush_info()
        self._reload_channel_group()
        self._open_processed_data() 
Example #19
Source File: usb_drive_copymode.py    From pi_video_looper with GNU General Public License v2.0 5 votes vote down vote up
def copyfile(self, src, dst, *, follow_symlinks=True):
        """Copy data from src to dst.

        If follow_symlinks is not set and src is a symbolic link, a new
        symlink will be created instead of copying the file it points to.

        """
        if shutil._samefile(src, dst):
            raise shutil.SameFileError("{!r} and {!r} are the same file".format(src, dst))

        for fn in [src, dst]:
            try:
                st = os.stat(fn)
            except OSError:
                # File most likely does not exist
                pass
            else:
                # XXX What about other special files? (sockets, devices...)
                if shutil.stat.S_ISFIFO(st.st_mode):
                    raise shutil.SpecialFileError("`%s` is a named pipe" % fn)

        if not follow_symlinks and os.path.islink(src):
            os.symlink(os.readlink(src), dst)
        else:
            size = os.stat(src).st_size
            with open(src, 'rb') as fsrc:
                with open(dst, 'wb') as fdst:
                    self.copyfileobj(fsrc, fdst, callback=self.draw_copy_progress, total=size)
        return dst 
Example #20
Source File: test_shutil.py    From ironpython3 with Apache License 2.0 4 votes vote down vote up
def test_module_all_attribute(self):
        self.assertTrue(hasattr(shutil, '__all__'))
        target_api = ['copyfileobj', 'copyfile', 'copymode', 'copystat',
                      'copy', 'copy2', 'copytree', 'move', 'rmtree', 'Error',
                      'SpecialFileError', 'ExecError', 'make_archive',
                      'get_archive_formats', 'register_archive_format',
                      'unregister_archive_format', 'get_unpack_formats',
                      'register_unpack_format', 'unregister_unpack_format',
                      'unpack_archive', 'ignore_patterns', 'chown', 'which',
                      'get_terminal_size', 'SameFileError']
        if hasattr(os, 'statvfs') or os.name == 'nt':
            target_api.append('disk_usage')
        self.assertEqual(set(shutil.__all__), set(target_api)) 
Example #21
Source File: test_shutil.py    From Fluid-Designer with GNU General Public License v3.0 4 votes vote down vote up
def test_module_all_attribute(self):
        self.assertTrue(hasattr(shutil, '__all__'))
        target_api = ['copyfileobj', 'copyfile', 'copymode', 'copystat',
                      'copy', 'copy2', 'copytree', 'move', 'rmtree', 'Error',
                      'SpecialFileError', 'ExecError', 'make_archive',
                      'get_archive_formats', 'register_archive_format',
                      'unregister_archive_format', 'get_unpack_formats',
                      'register_unpack_format', 'unregister_unpack_format',
                      'unpack_archive', 'ignore_patterns', 'chown', 'which',
                      'get_terminal_size', 'SameFileError']
        if hasattr(os, 'statvfs') or os.name == 'nt':
            target_api.append('disk_usage')
        self.assertEqual(set(shutil.__all__), set(target_api)) 
Example #22
Source File: extractor.py    From blogger-cli with MIT License 4 votes vote down vote up
def extract_static_files(ctx, file_name, file_path, dest_dir):
    """
    This function will look for static local files that were linked
    from inside ipynb file. The path is built dynamically according
    to the one provided in ipynb file.

    Eg: ('learning.mp4')
    The learning.mp4 file will be searched in same dir as of original
    ipynb file.

    Eg: ('../learning.mp4)
    Similarly, now blogger will look learning.mp4 in the parent dir of
    original ipynb file.

    NOTE: In cases where the ipynb file was previously converted and is
    located  inside the blog_dir then entire blog_dir will be searched
    for that image and the path that contain topic/ipynb_filename will
    be selected as static_path. What this means if You have to use same
    topic as before to make use of this.
    """

    orig_dir = Path(os.path.dirname(file_path))
    static_path = orig_dir / file_name
    file_name = os.path.basename(file_name)  # manage cases like ../../video.mp4

    # Detect if the original file is in blog dir itself
    blog_dir = Path(ctx.config.read(key=ctx.current_blog + ":blog_dir"))
    blog_dir = blog_dir.expanduser()

    is_inside_blog_dir = False
    if str(blog_dir) in file_path:
        is_inside_blog_dir = True

    # Provide the static files path if orig file is in blog_dir
    if not static_path.exists() and is_inside_blog_dir:
        dest_dir_parts = Path(dest_dir).parts
        topic_filename = Path(dest_dir_parts[-2]) / dest_dir_parts[-1]

        image_dirs = list(blog_dir.rglob(str(topic_filename)))

        while not static_path.exists() and image_dirs:
            static_path_dir = image_dirs.pop(0)
            static_path = static_path_dir / file_name

    if static_path.exists():
        static_path = static_path.resolve()
        dest_path = os.path.join(dest_dir, file_name)
        try:
            shutil.copyfile(str(static_path), dest_path)
        except shutil.SameFileError:
            pass

        return dest_path