本文整理匯總了Python中os.path.exists方法的典型用法代碼示例。如果您正苦於以下問題:Python path.exists方法的具體用法?Python path.exists怎麽用?Python path.exists使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類os.path
的用法示例。
在下文中一共展示了path.exists方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: gt_roidb
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import exists [as 別名]
def gt_roidb(self):
"""
Return the database of ground-truth regions of interest.
This function loads/saves from/to a cache file to speed up future calls.
"""
cache_file = osp.join(self.cache_path, self.name + '_gt_roidb.pkl')
if osp.exists(cache_file):
with open(cache_file, 'rb') as fid:
roidb = pickle.load(fid)
print('{} gt roidb loaded from {}'.format(self.name, cache_file))
return roidb
gt_roidb = [self._load_coco_annotation(index)
for index in self._image_index]
with open(cache_file, 'wb') as fid:
pickle.dump(gt_roidb, fid, pickle.HIGHEST_PROTOCOL)
print('wrote gt roidb to {}'.format(cache_file))
return gt_roidb
開發者ID:Sunarker,項目名稱:Collaborative-Learning-for-Weakly-Supervised-Object-Detection,代碼行數:21,代碼來源:coco.py
示例2: mock_requestsGithub
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import exists [as 別名]
def mock_requestsGithub(uri, headers={}, params={}):
if uri.endswith('contents'):
return_value = Mock(ok=True)
return_value.json.return_value = mock_files
return return_value
else:
targetFile = uri.replace('https://raw.githubusercontent.com/fakeuser/fakerepo/master/', path.join(base_url, ''))
if path.exists(targetFile):
f = open(targetFile, 'r')
lines = f.readlines()
text = ''.join(lines)
return_value = Mock(status_code=200)
return_value.text = text
return return_value
else:
return_value = Mock(status_code=404)
return return_value
示例3: load_configuration
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import exists [as 別名]
def load_configuration(descriptor):
""" Load configuration from the given descriptor. Could be
either a `spleeter:` prefixed embedded configuration name
or a file system path to read configuration from.
:param descriptor: Configuration descriptor to use for lookup.
:returns: Loaded description as dict.
:raise ValueError: If required embedded configuration does not exists.
:raise SpleeterError: If required configuration file does not exists.
"""
# Embedded configuration reading.
if descriptor.startswith(_EMBEDDED_CONFIGURATION_PREFIX):
name = descriptor[len(_EMBEDDED_CONFIGURATION_PREFIX):]
if not loader.is_resource(resources, f'{name}.json'):
raise SpleeterError(f'No embedded configuration {name} found')
with loader.open_text(resources, f'{name}.json') as stream:
return json.load(stream)
# Standard file reading.
if not exists(descriptor):
raise SpleeterError(f'Configuration file {descriptor} not found')
with open(descriptor, 'r') as stream:
return json.load(stream)
示例4: get
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import exists [as 別名]
def get(self, model_directory):
""" Ensures required model is available at given location.
:param model_directory: Expected model_directory to be available.
:raise IOError: If model can not be retrieved.
"""
# Expend model directory if needed.
if not isabs(model_directory):
model_directory = join(self.DEFAULT_MODEL_PATH, model_directory)
# Download it if not exists.
model_probe = join(model_directory, self.MODEL_PROBE_PATH)
if not exists(model_probe):
if not exists(model_directory):
makedirs(model_directory)
self.download(
model_directory.split(sep)[-1],
model_directory)
self.writeProbe(model_directory)
return model_directory
示例5: cache
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import exists [as 別名]
def cache(self, dataset, cache, wait):
""" Cache the given dataset if cache is enabled. Eventually waits for
cache to be available (useful if another process is already computing
cache) if provided wait flag is True.
:param dataset: Dataset to be cached if cache is required.
:param cache: Path of cache directory to be used, None if no cache.
:param wait: If caching is enabled, True is cache should be waited.
:returns: Cached dataset if needed, original dataset otherwise.
"""
if cache is not None:
if wait:
while not exists(f'{cache}.index'):
get_logger().info(
'Cache not available, wait %s',
self.WAIT_PERIOD)
time.sleep(self.WAIT_PERIOD)
cache_path = os.path.split(cache)[0]
os.makedirs(cache_path, exist_ok=True)
return dataset.cache(cache)
return dataset
示例6: extract
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import exists [as 別名]
def extract(self):
if(hasattr(cherrypy.request, 'json')):
if('dir' in cherrypy.request.json and cherrypy.request.json['dir']!='' and 'name' in cherrypy.request.json and cherrypy.request.json['name']!=''):
dir = cherrypy.request.json['dir']
name = cherrypy.request.json['name']
fdir = path.join(self.datapath, dir)
fp = path.join(fdir, name)
if(path.exists(fp)):
with zipfile.ZipFile(fp, "r") as z:
z.extractall(fdir)
return {'status': 'success', 'message': "File %s/%s extracted!"%(dir, name)}
else:
return {'status': 'error', 'message': "File doesn't exist!"}
else:
return {'status': 'error', 'message': "Invalid filename!"}
else:
return {'status': 'error', 'message': "No filename given!"}
示例7: ensure_permissions
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import exists [as 別名]
def ensure_permissions(mode_flags=stat.S_IWUSR):
"""decorator to ensure a filename has given permissions.
If changed, original permissions are restored after the decorated
modification.
"""
def decorator(f):
def modify(filename, *args, **kwargs):
m = chmod_perms(filename) if exists(filename) else mode_flags
if not m & mode_flags:
os.chmod(filename, m | mode_flags)
try:
return f(filename, *args, **kwargs)
finally:
# restore original permissions
if not m & mode_flags:
os.chmod(filename, m)
return modify
return decorator
# Open filename, checking for read permission
示例8: find_package_dirs
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import exists [as 別名]
def find_package_dirs(root_path):
""" Find python package directories in directory `root_path`
Parameters
----------
root_path : str
Directory to search for package subdirectories
Returns
-------
package_sdirs : set
Set of strings where each is a subdirectory of `root_path`, containing
an ``__init__.py`` file. Paths prefixed by `root_path`
"""
package_sdirs = set()
for entry in os.listdir(root_path):
fname = entry if root_path == '.' else pjoin(root_path, entry)
if isdir(fname) and exists(pjoin(fname, '__init__.py')):
package_sdirs.add(fname)
return package_sdirs
示例9: has_system_site_packages
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import exists [as 別名]
def has_system_site_packages(interpreter):
# TODO: unit-test
system_site_packages = check_output((
interpreter,
'-c',
# stolen directly from virtualenv's site.py
"""\
import site, os.path
print(
0
if os.path.exists(
os.path.join(os.path.dirname(site.__file__), 'no-global-site-packages.txt')
) else
1
)"""
))
system_site_packages = int(system_site_packages)
assert system_site_packages in (0, 1)
return bool(system_site_packages)
示例10: create_urls
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import exists [as 別名]
def create_urls(args):
urlcolumn = args.urlcolumn
result = list()
data = []
for f in args.url:
if(exists(f)):
data.extend(open(f))
else:
data.extend(f.split(','))
i = 1
for line in data:
if i > args.startrow:
line = line.strip()
k = line.split(',')
fid = k[0]
if(len(k) == 1):
fid = str(i)
urlcolumn = 0
result.append((fid,k[urlcolumn]))
i = i + 1
return result
示例11: compile_bundle_entry
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import exists [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
示例12: test_existing_removed
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import exists [as 別名]
def test_existing_removed(self):
# force an existing file
target = self.registry.records[('app', 'nothing.js')]
os.mkdir(dirname(target))
with open(target, 'w'):
pass
with pretty_logging(stream=mocks.StringIO()) as stream:
self.registry.process_package('app')
log = stream.getvalue()
self.assertIn(
"package 'app' has declared 3 entry points for the "
"'calmjs.artifacts' registry for artifact construction", log
)
log = stream.getvalue()
self.assertIn("removing existing export target at ", log)
self.assertFalse(exists(target))
示例13: test_pkg_manager_init_working_dir
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import exists [as 別名]
def test_pkg_manager_init_working_dir(self):
self.setup_requirements_json()
original = mkdtemp(self)
os.chdir(original)
cwd = mkdtemp(self)
target = join(cwd, 'requirements.json')
driver = cli.PackageManagerDriver(
pkg_manager_bin='mgr', pkgdef_filename='requirements.json',
dep_keys=('require',),
working_dir=cwd,
)
driver.pkg_manager_init('calmpy.pip')
self.assertFalse(exists(join(original, 'requirements.json')))
self.assertTrue(exists(target))
with open(target) as fd:
result = json.load(fd)
self.assertEqual(result, {
"require": {"setuptools": "25.1.6"},
"name": "calmpy.pip",
})
示例14: test_toolchain_standard_not_implemented
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import exists [as 別名]
def test_toolchain_standard_not_implemented(self):
spec = Spec()
with self.assertRaises(NotImplementedError):
self.toolchain(spec)
with self.assertRaises(NotImplementedError):
self.toolchain.assemble(spec)
with self.assertRaises(NotImplementedError):
self.toolchain.link(spec)
# Check that the build_dir is set on the spec based on tempfile
self.assertTrue(spec['build_dir'].startswith(
realpath(tempfile.gettempdir())))
# Also that it got deleted properly.
self.assertFalse(exists(spec['build_dir']))
示例15: test_toolchain_standard_build_dir_set
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import exists [as 別名]
def test_toolchain_standard_build_dir_set(self):
spec = Spec()
spec['build_dir'] = mkdtemp(self)
with self.assertRaises(NotImplementedError):
self.toolchain(spec)
# Manually specified build_dirs do not get deleted from the
# filesystem
self.assertTrue(exists(spec['build_dir']))
not_exist = join(spec['build_dir'], 'not_exist')
spec['build_dir'] = not_exist
with pretty_logging(stream=StringIO()) as s:
with self.assertRaises(OSError):
# well, dir does not exist
self.toolchain(spec)
# Manually specified build_dirs do not get modified if they just
# simply don't exist.
self.assertEqual(spec['build_dir'], not_exist)
self.assertIn(not_exist, s.getvalue())
self.assertIn("is not a directory", s.getvalue())