本文整理匯總了Python中shutil.Error方法的典型用法代碼示例。如果您正苦於以下問題:Python shutil.Error方法的具體用法?Python shutil.Error怎麽用?Python shutil.Error使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類shutil
的用法示例。
在下文中一共展示了shutil.Error方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_copytree_with_broken_symlink_fail
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import Error [as 別名]
def test_copytree_with_broken_symlink_fail(smb_share):
src_dirname = "%s\\source" % smb_share
dst_dirname = "%s\\target" % smb_share
mkdir(src_dirname)
symlink("%s\\dir" % src_dirname, "%s\\link" % src_dirname, target_is_directory=True)
symlink("%s\\file.txt" % src_dirname, "%s\\link.txt" % src_dirname)
with pytest.raises(shutil.Error) as actual:
copytree(src_dirname, dst_dirname)
assert len(actual.value.args[0]) == 2
err1 = actual.value.args[0][0]
err2 = actual.value.args[0][1]
assert err1[0] == "%s\\link" % src_dirname
assert err1[1] == "%s\\link" % dst_dirname
assert "No such file or directory" in err1[2]
assert err2[0] == "%s\\link.txt" % src_dirname
assert err2[1] == "%s\\link.txt" % dst_dirname
assert "No such file or directory" in err2[2]
示例2: _ShareUpload
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import Error [as 別名]
def _ShareUpload(self, source_log: Text, share: Text):
"""Copy the log file to a network file share.
Args:
source_log: Path to the source log file to be copied.
share: The destination share to copy the file to.
Raises:
LogCopyError: Failure to mount share and copy log.
"""
creds = LogCopyCredentials()
username = creds.GetUsername()
password = creds.GetPassword()
mapper = drive_map.DriveMap()
result = mapper.MapDrive('l:', share, username, password)
if result:
destination = self._GetLogFileName()
try:
shutil.copy(source_log, destination)
except shutil.Error:
raise LogCopyError('Log copy failed.')
mapper.UnmapDrive('l:')
else:
raise LogCopyError('Drive mapping failed.')
示例3: CreateDirectories
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import Error [as 別名]
def CreateDirectories(path: Text):
"""Create directory if the path to a file doesn't exist.
Args:
path: The full file path to where a file will be placed.
Raises:
Error: Failure creating the requested directory.
"""
dirname = os.path.dirname(path)
if not os.path.isdir(dirname):
logging.debug('Creating directory %s ', dirname)
try:
os.makedirs(dirname)
except (shutil.Error, OSError):
raise Error('Unable to make directory: %s' % dirname)
示例4: Move
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import Error [as 別名]
def Move(src: Text, dst: Text):
"""Move a file from src to dst.
Python's os.rename doesn't support overwrite on Windows.
Args:
src: The full file path to the source.
dst: The full file path to the destination.
Raises:
Error: Failure moving the file.
"""
try:
Remove(dst)
os.rename(src, dst)
except OSError as e:
raise Error('Failure moving file from %s to %s. (%s)' % (src, dst, str(e)))
示例5: start_mysql_func
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import Error [as 別名]
def start_mysql_func(self, start_tool=None, options=None):
# Starting MySQL
logger.info("Starting MySQL server: ")
if start_tool is None:
args = self.start_mysql
else:
args = start_tool
if options is not None:
start_command = "{} {}".format(args, options)
else:
start_command = args
status, output = subprocess.getstatusoutput(start_command)
if status == 0:
logger.info("Starting MySQL ...")
logger.info(output)
return True
else:
logger.error("Error occurred while starting MySQL!")
logger.error(output)
raise RuntimeError("Error occurred while starting MySQL!")
示例6: copy
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import Error [as 別名]
def copy(self, options=None, datadir=None):
"""
Function for running:
xtrabackup --copy-back
giving chown to datadir
starting mysql
:return: True if succeeded. Error if failed
"""
logger.info("Copying Back Already Prepared Final Backup:")
if len(os.listdir(self.datadir if datadir is None else datadir)) > 0:
logger.info("MySQL Datadir is not empty!")
return False
else:
self.run_xtra_copyback(datadir=datadir)
self.giving_chown(datadir=datadir)
self.start_mysql_func(options=options)
return True
示例7: saveProxyLog
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import Error [as 別名]
def saveProxyLog(name, config):
'''
Save proxy log database into a new file
:param name: Name of file to save data into (should be .db)
:param config: Proxy ConfigParser object from proxy.ini
:return: None
'''
log = config.get("DATABASE", "filename")
oldpath = os.path.join(faradayHelper.userPath, 'lib', log)
newpath = os.path.join(faradayHelper.userPath, 'lib', name)
try:
shutil.move(oldpath, newpath)
sys.exit(0)
except shutil.Error as e:
logger.error(e)
except IOError as e:
logger.error(e)
示例8: saveTelemetryLog
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import Error [as 別名]
def saveTelemetryLog(name, config):
'''
Save telemetry log database into a new file
:param name: Name of file to save data into (should be .db)
:param config: Telemetry ConfigParser object from telmetry.ini
:return: None
'''
log = config.get("DATABASE", "filename")
oldpath = os.path.join(faradayHelper.userPath, 'lib', log)
newpath = os.path.join(faradayHelper.userPath, 'lib', name)
try:
shutil.move(oldpath, newpath)
sys.exit(0)
except shutil.Error as e:
logger.error(e)
except IOError as e:
logger.error(e)
示例9: test_copytree_named_pipe
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import Error [as 別名]
def test_copytree_named_pipe(self):
os.mkdir(TESTFN)
try:
subdir = os.path.join(TESTFN, "subdir")
os.mkdir(subdir)
pipe = os.path.join(subdir, "mypipe")
os.mkfifo(pipe)
try:
shutil.copytree(TESTFN, TESTFN2)
except shutil.Error as e:
errors = e.args[0]
self.assertEqual(len(errors), 1)
src, dst, error_msg = errors[0]
self.assertEqual("`%s` is a named pipe" % pipe, error_msg)
else:
self.fail("shutil.Error should have been raised")
finally:
shutil.rmtree(TESTFN, ignore_errors=True)
shutil.rmtree(TESTFN2, ignore_errors=True)
示例10: moveKeyFilesToCorrectLocations
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import Error [as 別名]
def moveKeyFilesToCorrectLocations(keys_dir, pkdir, skdir):
for key_file in os.listdir(keys_dir):
if key_file.endswith(".key"):
try:
shutil.move(os.path.join(keys_dir, key_file),
os.path.join(pkdir, key_file))
except shutil.Error as ex:
# print(ex)
pass
if key_file.endswith(".key_secret"):
try:
shutil.move(os.path.join(keys_dir, key_file),
os.path.join(skdir, key_file))
except shutil.Error as ex:
# print(ex)
pass
示例11: test_copytree_named_pipe
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import Error [as 別名]
def test_copytree_named_pipe(self):
os.mkdir(TESTFN)
try:
subdir = os.path.join(TESTFN, "subdir")
os.mkdir(subdir)
pipe = os.path.join(subdir, "mypipe")
os.mkfifo(pipe)
try:
shutil.copytree(TESTFN, TESTFN2)
except shutil.Error as e:
errors = e.args[0]
self.assertEqual(len(errors), 1)
src, dst, error_msg = errors[0]
self.assertEqual("`%s` is a named pipe" % pipe, error_msg)
else:
self.fail("shutil.Error should have been raised")
finally:
shutil.rmtree(TESTFN, ignore_errors=True)
shutil.rmtree(TESTFN2, ignore_errors=True)
示例12: copytree
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import Error [as 別名]
def copytree(src, dst, copy_function=shutil.copy2, symlinks=False):
"Implementation adapted from https://docs.python.org/3/library/shutil.html#copytree-example'."
os.makedirs(dst)
names = os.listdir(src)
errors = []
for name in names:
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
try:
if symlinks and os.path.islink(srcname):
linkto = os.readlink(srcname)
os.symlink(linkto, dstname)
elif os.path.isdir(srcname):
copytree(srcname, dstname, copy_function, symlinks)
else:
copy_function(srcname, dstname)
except OSError as why:
errors.append((srcname, dstname, str(why)))
# catch the Error from the recursive copytree so that we can
# continue with other files
except shutil.Error as err:
errors.extend(err.args[0])
if errors:
raise shutil.Error(errors)
示例13: create_backup
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import Error [as 別名]
def create_backup(self, path):
logger.debug("Create backup of '{}'.".format(os.path.relpath(path)))
path_backup = path + '~'
if os.path.isfile(path_backup):
raise RuntimeError(
"Failed to create backup, file already exists: '{}'.".format(
os.path.relpath(path_backup)))
try:
self._copy2(path, path_backup)
yield path_backup
except: # noqa roll-back
logger.more("Error occured, restoring backup...")
self._copy2(path_backup, path)
raise
finally:
logger.debug("Remove backup of '{}'.".format(os.path.relpath(path)))
self._remove(path_backup)
示例14: set_assessor_status
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import Error [as 別名]
def set_assessor_status(self, status):
"""
Set the status of the assessor based on passed value
:param status: Value to set the procstatus to
:except: All catchable errors.
:return: None
"""
# Connection to Xnat
try:
with get_interface(host=self.host) as intf:
assessor = self.assr_handler.select_assessor(intf)
if assessor.exists():
dtype = DEFAULT_DATATYPE
if self.assr_handler.get_proctype() == 'FS':
dtype = DEFAULT_FS_DATATYPE
former_status = assessor.attrs.get('%s/procstatus' % dtype)
if former_status == JOB_RUNNING:
assessor.attrs.set('%s/procstatus' % dtype, status)
msg = ' - job status set to %s'
self.print_msg(msg % str(status))
except XnatAuthentificationError as e:
print(('Failed to connect to XNAT. Error: ', e))
pass
示例15: remove
# 需要導入模塊: import shutil [as 別名]
# 或者: from shutil import Error [as 別名]
def remove(self, filelist):
"""remove files from given path"""
for file in filelist:
if os.path.isfile(file):
Log.info(self, "Removing {0:65}".format(file), end=' ')
os.remove(file)
Log.info(self, "{0}".format("[" + Log.ENDC + "Done" +
Log.OKBLUE + "]"))
Log.debug(self, 'file Removed')
if os.path.isdir(file):
try:
Log.info(self, "Removing {0:65}".format(file), end=' ')
shutil.rmtree(file)
Log.info(self, "{0}".format("[" + Log.ENDC + "Done" +
Log.OKBLUE + "]"))
except shutil.Error as e:
Log.debug(self, "{err}".format(err=str(e.reason)))
Log.error(self, 'Unable to Remove file ')