def makedir(self, tarinfo, targetpath):
"""Make a directory called targetpath.
"""
try:
# Use a safe mode for the directory, the real mode is set
# later in _extract_member().
os.mkdir(targetpath, 0o700)
except EnvironmentError as e:
if e.errno != errno.EEXIST:
raise
python类EEXIST的实例源码
def ensure_dir(path):
"""os.path.makedirs without EEXIST."""
try:
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST:
raise
def _makedirs_31(path, exist_ok=False):
try:
os.makedirs(path)
except OSError as exc:
if not exist_ok or exc.errno != errno.EEXIST:
raise
# rely on compatibility behavior until mode considerations
# and exists_ok considerations are disentangled.
# See https://github.com/pypa/setuptools/pull/1083#issuecomment-315168663
def mkdtemp(suffix=None, prefix=None, dir=None):
"""User-callable function to create and return a unique temporary
directory. The return value is the pathname of the directory.
Arguments are as for mkstemp, except that the 'text' argument is
not accepted.
The directory is readable, writable, and searchable only by the
creating user.
Caller is responsible for deleting the directory when done with it.
"""
prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)
names = _get_candidate_names()
if output_type is bytes:
names = map(_os.fsencode, names)
for seq in range(TMP_MAX):
name = next(names)
file = _os.path.join(dir, prefix + name + suffix)
try:
_os.mkdir(file, 0o700)
except FileExistsError:
continue # try again
except PermissionError:
# This exception is thrown when a directory with the chosen name
# already exists on windows.
if (_os.name == 'nt' and _os.path.isdir(dir) and
_os.access(dir, _os.W_OK)):
continue
else:
raise
return file
raise FileExistsError(_errno.EEXIST,
"No usable temporary directory name found")
def mktemp(suffix="", prefix=template, dir=None):
"""User-callable function to return a unique temporary file name. The
file is not created.
Arguments are similar to mkstemp, except that the 'text' argument is
not accepted, and suffix=None, prefix=None and bytes file names are not
supported.
THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file name may
refer to a file that did not exist at some point, but by the time
you get around to creating it, someone else may have beaten you to
the punch.
"""
## from warnings import warn as _warn
## _warn("mktemp is a potential security risk to your program",
## RuntimeWarning, stacklevel=2)
if dir is None:
dir = gettempdir()
names = _get_candidate_names()
for seq in range(TMP_MAX):
name = next(names)
file = _os.path.join(dir, prefix + name + suffix)
if not _exists(file):
return file
raise FileExistsError(_errno.EEXIST,
"No usable temporary filename found")
def mkdir_p_polyfill(path, perms, exist_ok):
"""Make directories including parents.
Python >= 3.2 doesn't need this because the exist_ok parameter is there.
However, earlier python versions don't have that.
See http://stackoverflow.com/questions/600268/mkdir-p-functionality-in-python/600612#600612
"""
try:
os.makedirs(path, perms)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def __init__(self, *args, **kwargs):
#super(PcapPlugin, self).__init__(*args, **kwargs)
plugin.Plugin.__init__(self, *args, **kwargs)
try:
os.makedirs(self.__pcap_dir__)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
def acquire(self, timeout=None):
""" Acquire the lock.
Creates the PID file for this lock, or raises an error if
the lock could not be acquired.
"""
timeout = timeout if timeout is not None else self.timeout
end_time = time.time()
if timeout is not None and timeout > 0:
end_time += timeout
while True:
try:
write_pid_to_pidfile(self.path)
except OSError as exc:
if exc.errno == errno.EEXIST:
# The lock creation failed. Maybe sleep a bit.
if time.time() > end_time:
if timeout is not None and timeout > 0:
raise LockTimeout("Timeout waiting to acquire"
" lock for %s" %
self.path)
else:
raise AlreadyLocked("%s is already locked" %
self.path)
time.sleep(timeout is not None and timeout / 10 or 0.1)
else:
raise LockFailed("failed to create %s" % self.path)
else:
return
def acquire(self, timeout=None):
timeout = timeout if timeout is not None else self.timeout
end_time = time.time()
if timeout is not None and timeout > 0:
end_time += timeout
if timeout is None:
wait = 0.1
else:
wait = max(0, timeout / 10)
while True:
try:
os.mkdir(self.lock_file)
except OSError:
err = sys.exc_info()[1]
if err.errno == errno.EEXIST:
# Already locked.
if os.path.exists(self.unique_name):
# Already locked by me.
return
if timeout is not None and time.time() > end_time:
if timeout > 0:
raise LockTimeout("Timeout waiting to acquire"
" lock for %s" %
self.path)
else:
# Someone else has the lock.
raise AlreadyLocked("%s is already locked" %
self.path)
time.sleep(wait)
else:
# Couldn't create the lock for some other reason
raise LockFailed("failed to create %s" % self.lock_file)
else:
open(self.unique_name, "wb").close()
return
def makedir(self, tarinfo, targetpath):
"""Make a directory called targetpath.
"""
try:
# Use a safe mode for the directory, the real mode is set
# later in _extract_member().
os.mkdir(targetpath, 0o700)
except EnvironmentError as e:
if e.errno != errno.EEXIST:
raise
def ensure_dir(path):
"""os.path.makedirs without EEXIST."""
try:
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST:
raise
def _makedirs_31(path, exist_ok=False):
try:
os.makedirs(path)
except OSError as exc:
if not exist_ok or exc.errno != errno.EEXIST:
raise
# rely on compatibility behavior until mode considerations
# and exists_ok considerations are disentangled.
# See https://github.com/pypa/setuptools/pull/1083#issuecomment-315168663
def cached_inventory(self, filters, cache_path=None, cache_ttl=3600, refresh=False, ):
"""
Wrapper method implementing caching functionality over list_inventory.
:param dict filters: A dictionary of pyVmomi virtual machine attribute key-value filters.
:param str cache_path: A path for caching inventory list data. Quite a necessity for large environments.
:param int cache_ttl: Integer Inventory list data cache Time To Live in seconds. (cache Expiration period)
:param boolean refresh: Setting this True, triggers a cache refresh. Fresh data is fetched.
:return: An Ansible pluggable dynamic inventory, as a Python json serializable dictionary.
"""
if refresh:
return self.list_and_save(filters, cache_path)
else:
if os.path.isfile(cache_path) and time() - os.stat(cache_path).st_mtime < cache_ttl:
try:
with open(cache_path) as f:
data = load(f)
return data
except (ValueError, IOError):
return self.list_and_save(filters, cache_path)
else:
if not os.path.exists(os.path.dirname(cache_path)):
try:
if cache_path:
os.makedirs(os.path.dirname(cache_path))
else:
raise OSError("[Error] cache_path not defined: {}".format(cache_path))
# handle race condition
except OSError as exc:
if exc.errno == errno.EACCES:
print("{}".format(str(exc)))
exit(1)
elif exc.errno != errno.EEXIST:
raise
return self.list_and_save(filters, cache_path)
def visitInterface (self, node):
package = qualifiedName(node.scopedName()[:-1] + ['jni'])
# Ensure the directory structure is there
path = os.path.join(*package.split('.'))
try:
os.makedirs(path)
except OSError, e:
# If the leaf directory already existed (or was created in the
# interim), ignore the error
if e.errno != errno.EEXIST:
raise
# Override library name with argument
libname = self.__options.get('libname', None)
if not libname:
libname = node.scopedName()[-2].lower() + 'jni'
# Generate the stub
stubCode = StubClass(package, libname).generate(node)
stubFile = os.path.join(path, stubName(node) + '.java')
stubCode.write(javacode.SourceFile(open(stubFile, 'w')))
# Generate the helper
interface = qualifiedName(node.scopedName())
helperCode = HelperClass(package, interface).generate(node)
helperFile = os.path.join(path, helperName(node) + '.java')
helperCode.write(javacode.SourceFile(open(helperFile, 'w')))
# Generate the POA
poaCode = POAClass(package, libname).generate(node)
poaFile = os.path.join(path, poaName(node) + '.java')
poaCode.write(javacode.SourceFile(open(poaFile, 'w')))
def make_sure_path_exists(path):
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
# Debug model info
def make_sure_path_exists(path):
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
# Run model
def make_sure_path_exists(path):
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
# Run model, use current timestamp for output directory name
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def make_dirs(file_path):
"""Make the directories for a file path
:param file_path: file path to be created if it doesn't exist
:type file_path: str
:return: None
"""
try:
os.makedirs(os.path.dirname(file_path))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise # pragma: no cover