当前位置: 首页>>代码示例>>Python>>正文


Python path.exists方法代码示例

本文整理汇总了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 
开发者ID:CLARIAH,项目名称:grlc,代码行数:19,代码来源:mock_data.py

示例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) 
开发者ID:deezer,项目名称:spleeter,代码行数:24,代码来源:configuration.py

示例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 
开发者ID:deezer,项目名称:spleeter,代码行数:21,代码来源:__init__.py

示例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 
开发者ID:deezer,项目名称:spleeter,代码行数:23,代码来源:dataset.py

示例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!"} 
开发者ID:SecPi,项目名称:SecPi,代码行数:20,代码来源:alarmdata.py

示例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 
开发者ID:matthew-brett,项目名称:delocate,代码行数:26,代码来源:tools.py

示例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 
开发者ID:matthew-brett,项目名称:delocate,代码行数:22,代码来源:tools.py

示例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) 
开发者ID:edmundmok,项目名称:mealpy,代码行数:21,代码来源:venv_update.py

示例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 
开发者ID:koenbuyens,项目名称:securityheaders,代码行数:25,代码来源:command_line.py

示例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 
开发者ID:calmjs,项目名称:calmjs,代码行数:24,代码来源:toolchain.py

示例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)) 
开发者ID:calmjs,项目名称:calmjs,代码行数:20,代码来源:test_artifact.py

示例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",
        }) 
开发者ID:calmjs,项目名称:calmjs,代码行数:25,代码来源:test_cli.py

示例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'])) 
开发者ID:calmjs,项目名称:calmjs,代码行数:19,代码来源:test_toolchain.py

示例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()) 
开发者ID:calmjs,项目名称:calmjs,代码行数:26,代码来源:test_toolchain.py


注:本文中的os.path.exists方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。