本文整理匯總了Python中shutil.copytree方法的典型用法代碼示例。如果您正苦於以下問題:Python shutil.copytree方法的具體用法?Python shutil.copytree怎麽用?Python shutil.copytree使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類shutil
的用法示例。
在下文中一共展示了shutil.copytree方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __call__
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copytree [as 別名]
def __call__(self, args, env):
samples_dir = env.get('samples-dir')
for label in ("cat", "dog"):
dest = os.path.join(samples_dir, label)
if os.path.exists(dest):
raise VergeMLError("Directory {} already exists in samples dir: {}".format(label, dest))
print("Downloading cats and dogs to {}.".format(samples_dir))
src_dir = self.download_files([(_URL, "catsdogs.zip")], env)
path = os.path.join(src_dir, "catsdogs.zip")
print("Extracting data.")
zipf = zipfile.ZipFile(path, 'r')
zipf.extractall(src_dir)
zipf.close()
for file, dest in (("PetImages/Dog", "dog"), ("PetImages/Cat", "cat")):
shutil.copytree(os.path.join(src_dir, file), os.path.join(samples_dir, dest))
shutil.rmtree(src_dir)
# WTF?
os.unlink(os.path.join(samples_dir, "cat", "666.jpg"))
os.unlink(os.path.join(samples_dir, "dog", "11702.jpg"))
print("Finished downloading cats and dogs.")
示例2: save_dictionary
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copytree [as 別名]
def save_dictionary(config):
"""
:param config: config
:return:
"""
if config.save_dict is True:
if os.path.exists(config.dict_directory):
shutil.rmtree(config.dict_directory)
if not os.path.isdir(config.dict_directory):
os.makedirs(config.dict_directory)
config.word_dict_path = "/".join([config.dict_directory, config.word_dict])
config.label_dict_path = "/".join([config.dict_directory, config.label_dict])
print("word_dict_path : {}".format(config.word_dict_path))
print("label_dict_path : {}".format(config.label_dict_path))
save_dict2file(config.create_alphabet.word_alphabet.words2id, config.word_dict_path)
save_dict2file(config.create_alphabet.label_alphabet.words2id, config.label_dict_path)
# copy to mulu
print("copy dictionary to {}".format(config.save_dir))
shutil.copytree(config.dict_directory, "/".join([config.save_dir, config.dict_directory]))
# load data / create alphabet / create iterator
示例3: tar_and_copy_usr_dir
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copytree [as 別名]
def tar_and_copy_usr_dir(usr_dir, train_dir):
"""Package, tar, and copy usr_dir to GCS train_dir."""
tf.logging.info("Tarring and pushing t2t_usr_dir.")
usr_dir = os.path.abspath(os.path.expanduser(usr_dir))
# Copy usr dir to a temp location
top_dir = os.path.join(tempfile.gettempdir(), "t2t_usr_container")
tmp_usr_dir = os.path.join(top_dir, usr_dir_lib.INTERNAL_USR_DIR_PACKAGE)
shutil.rmtree(top_dir, ignore_errors=True)
shutil.copytree(usr_dir, tmp_usr_dir)
# Insert setup.py if one does not exist
top_setup_fname = os.path.join(top_dir, "setup.py")
setup_file_str = get_setup_file(
name="DummyUsrDirPackage",
packages=get_requirements(usr_dir)
)
with tf.gfile.Open(top_setup_fname, "w") as f:
f.write(setup_file_str)
usr_tar = _tar_and_copy(top_dir, train_dir)
return usr_tar
示例4: compile_bundle_entry
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copytree [as 別名]
def compile_bundle_entry(self, spec, entry):
"""
Handler for each entry for the bundle method of the compile
process. This copies the source file or directory into the
build directory.
"""
modname, source, target, modpath = entry
bundled_modpath = {modname: modpath}
bundled_target = {modname: target}
export_module_name = []
if isfile(source):
export_module_name.append(modname)
copy_target = join(spec[BUILD_DIR], target)
if not exists(dirname(copy_target)):
makedirs(dirname(copy_target))
shutil.copy(source, copy_target)
elif isdir(source):
copy_target = join(spec[BUILD_DIR], modname)
shutil.copytree(source, copy_target)
return bundled_modpath, bundled_target, export_module_name
示例5: Run
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copytree [as 別名]
def Run(self):
remove_existing = False
try:
src = self._args[0]
dst = self._args[1]
if len(self._args) > 2:
remove_existing = self._args[2]
except IndexError:
raise ActionError('Unable to determine source and destination from %s.' %
str(self._args))
try:
if os.path.exists(dst) and remove_existing:
logging.info('Deleting existing destination: %s', dst)
shutil.rmtree(dst)
except (shutil.Error, OSError) as e:
raise ActionError('Unable to delete existing destination folder %s: %s' %
(dst, str(e)))
try:
logging.info('Copying directory: %s to %s', src, dst)
shutil.copytree(src, dst)
except (shutil.Error, OSError) as e:
raise ActionError('Unable to copy %s to %s: %s' % (src, dst, str(e)))
示例6: testReadResultFromAlternateDir
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copytree [as 別名]
def testReadResultFromAlternateDir(self):
context = StorageOnlyContext()
otherdir_path = os.path.join(encoder_configuration.conf.sysdir(),
'otherdir')
os.mkdir(otherdir_path)
cache = encoder.EncodingDiskCache(context)
other_cache = encoder.EncodingDiskCache(context, scoredir='otherdir')
my_encoder = encoder.Encoder(
context,
encoder.OptionValueSet(encoder.OptionSet(), '--parameters'))
cache.StoreEncoder(my_encoder)
videofile = encoder.Videofile('x/foo_640_480_20.yuv')
my_encoding = encoder.Encoding(my_encoder, 123, videofile)
testresult = {'foo': 'bar'}
my_encoding.result = testresult
cache.StoreEncoding(my_encoding)
my_encoding.result = None
result = other_cache.ReadEncodingResult(my_encoding)
self.assertIsNone(result)
shutil.rmtree(otherdir_path)
shutil.copytree(encoder_configuration.conf.workdir(), otherdir_path)
result = other_cache.ReadEncodingResult(my_encoding)
self.assertEquals(result, testresult)
示例7: copy_compiled_libs
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copytree [as 別名]
def copy_compiled_libs(project_dir, decompiled_dir):
compiled_libs_dir = os.path.join(project_dir, "libs")
decompiled_libs_dir = os.path.join(decompiled_dir, "lib")
if not os.path.exists(compiled_libs_dir):
return
if not os.path.exists(decompiled_libs_dir):
shutil.copytree(compiled_libs_dir, decompiled_libs_dir)
return
for abi in os.listdir(decompiled_libs_dir):
dst = os.path.join(decompiled_libs_dir, abi)
src = os.path.join(compiled_libs_dir, abi)
if not os.path.exists(src) and abi == 'armeabi':
src = os.path.join(compiled_libs_dir, 'armeabi-v7a')
logger.warning('Use armeabi-v7a for armeabi')
if not os.path.exists(src):
raise Exception("ABI %s is not supported!" % abi)
libnc = os.path.join(src, LIBNATIVECODE)
shutil.copy(libnc, dst)
示例8: rsync_offline_dir
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copytree [as 別名]
def rsync_offline_dir(outputDir):
"""
Copy the pyGSTi 'offline' directory into `outputDir` by creating or updating
any outdated files as needed.
"""
destDir = _os.path.join(str(outputDir), "offline")
offlineDir = _os.path.join(_os.path.dirname(_os.path.abspath(__file__)),
"templates", "offline") # TODO package resources?
if not _os.path.exists(destDir):
_shutil.copytree(offlineDir, destDir)
else:
for dirpath, _, filenames in _os.walk(str(offlineDir)):
for nm in filenames:
srcnm = _os.path.join(dirpath, nm)
relnm = _os.path.relpath(srcnm, offlineDir)
destnm = _os.path.join(destDir, relnm)
if not _os.path.isfile(destnm) or \
(_os.path.getmtime(destnm) < _os.path.getmtime(srcnm)):
_shutil.copyfile(srcnm, destnm)
#print("COPYING to %s" % destnm)
示例9: test_tutorials
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copytree [as 別名]
def test_tutorials():
with TemporaryDirectory() as tmp:
tmp_path = Path(tmp)
# Copy tutorial file resources
for f_path in _TUTORIAL_FILES:
src = _TUTORIALS_ROOT / f_path
dest = tmp_path / f_path
dest.parent.mkdir(parents=True, exist_ok=True)
if src.is_dir():
shutil.copytree(src, dest)
else:
shutil.copy(src, dest)
# Emit a test for each notebook
for nb_path in notebooks_in_path(_TUTORIALS_ROOT):
rel_path = nb_path.relative_to(_TUTORIALS_ROOT)
workdir = tmp_path / rel_path.parent
workdir.mkdir(parents=True, exist_ok=True)
description = "Running notebook {}".format(rel_path)
yield attr(description=description)(run_notebook), nb_path, workdir
示例10: update_default
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copytree [as 別名]
def update_default(cls) -> "TrustStoresRepository":
"""Update the default trust stores used by SSLyze.
The latest stores will be downloaded from https://github.com/nabla-c0d3/trust_stores_observatory.
"""
temp_path = Path(mkdtemp())
try:
# Download the latest trust stores
archive_path = temp_path / "trust_stores_as_pem.tar.gz"
urlretrieve(cls._UPDATE_URL, archive_path)
# Extract the archive
extract_path = temp_path / "extracted"
tarfile.open(archive_path).extractall(extract_path)
# Copy the files to SSLyze and overwrite the existing stores
shutil.rmtree(cls._DEFAULT_TRUST_STORES_PATH)
shutil.copytree(extract_path, cls._DEFAULT_TRUST_STORES_PATH)
finally:
shutil.rmtree(temp_path)
# Re-generate the default repo - not thread-safe
cls._DEFAULT_REPOSITORY = cls(cls._DEFAULT_TRUST_STORES_PATH)
return cls._DEFAULT_REPOSITORY
示例11: export_protos
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copytree [as 別名]
def export_protos(destination):
"""Exports the compiled protos for the bundle.
The engine initialization process has already built all protos and made them
importable as `PB`. We rely on `PB.__path__` because this allows the
`--proto-override` flag to work.
Args:
* repo (RecipeRepo) - The repo to export.
* destination (str) - The absolute path we're exporting to (we'll export to
a subfolder `_pb/PB`).
"""
shutil.copytree(
PB_PATH[0], # root of generated PB folder.
os.path.join(destination, '_pb', 'PB'),
ignore=lambda _base, names: [n for n in names if n.endswith('.pyc')],
)
示例12: copy
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copytree [as 別名]
def copy(src,dst):
if type(src) == list:
if type(dst) == list:
try:
for i in range(0,10000000):
if os.path.isfile(src[i]):
shutil.copy(src[i], dst[i])
else:
shutil.copytree(src[i], dst[i]+'/'+src[i])
except IndexError:
pass
else:
for src_el in src:
if os.path.isfile(src_el):
shutil.copy(src_el,dst)
else:
shutil.copytree(src_el,dst+'/'+src_el)
else:
if os.path.isfile(src):
shutil.copy(src,dst)
else:
shutil.copytree(src,dst+'/'+src)
示例13: move
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copytree [as 別名]
def move(src,dst):
if type(src) == list:
if type(dst) == list:
try:
for i in range(0,10000000):
if os.path.isfile(src[i]):
shutil.move(src[i], dst[i])
else:
shutil.copytree(src[i], dst[i]+'/'+src[i])
shutil.rmtree(src[i])
except IndexError:
pass
else:
for src_el in src:
if os.path.isfile(src_el):
shutil.move(src_el,dst)
else:
shutil.copytree(src_el,dst+'/'+src_el)
shutil.rmtree(src_el)
else:
if os.path.isfile(src):
shutil.move(src,dst)
else:
shutil.copytree(src,dst+'/'+src)
shutil.rmtree(src)
示例14: _build_autotools
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copytree [as 別名]
def _build_autotools(self):
""" Test autotools integration """
# Copy autotools directory to build folder
shutil.copytree(os.path.join(self.source_folder, "autotools"), os.path.join(self.build_folder, "autotools"))
with tools.chdir("autotools"):
self.run("{} --install --verbose -Wall".format(os.environ["AUTORECONF"]), win_bash=tools.os_info.is_windows)
tools.mkdir(self._package_folder)
conf_args = [
"--prefix={}".format(tools.unix_path(self._package_folder)),
"--enable-shared", "--enable-static",
]
os.mkdir("bin_autotools")
with tools.chdir("bin_autotools"):
with self._build_context():
autotools = AutoToolsBuildEnvironment(self, win_bash=tools.os_info.is_windows)
autotools.libs = []
autotools.configure(args=conf_args, configure_dir=os.path.join(self.build_folder, "autotools"))
autotools.make(args=["V=1", "-j1"])
autotools.install()
示例15: _copy_sources
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import copytree [as 別名]
def _copy_sources(self):
# Copy CMakeLists wrapper
shutil.copy(os.path.join(self.source_folder, "CMakeLists.txt"), "CMakeLists.txt")
# Copy patches
if "patches" in self.conan_data:
if not os.path.exists("patches"):
os.mkdir("patches")
for patch in self.conan_data["patches"][self.version]:
shutil.copy(os.path.join(self.source_folder, patch["patch_file"]),
"patches")
# Copy PhysX source code
subfolders_to_copy = [
"pxshared",
os.path.join("externals", self._get_cmakemodules_subfolder()),
os.path.join("physx", "compiler"),
os.path.join("physx", "include"),
os.path.join("physx", "source")
]
for subfolder in subfolders_to_copy:
shutil.copytree(os.path.join(self.source_folder, self._source_subfolder, subfolder),
os.path.join(self._source_subfolder, subfolder))