Python os.path.exists() Examples

The following are 40 code examples for showing how to use os.path.exists(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module os.path , or try the search function .

Example 1
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 
Example 2
Project: grlc   Author: CLARIAH   File: mock_data.py    License: MIT License 6 votes vote down vote up
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 
Example 3
Project: spleeter   Author: deezer   File: configuration.py    License: MIT License 6 votes vote down vote up
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) 
Example 4
Project: spleeter   Author: deezer   File: __init__.py    License: MIT License 6 votes vote down vote up
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 
Example 5
Project: spleeter   Author: deezer   File: dataset.py    License: MIT License 6 votes vote down vote up
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 
Example 6
Project: SecPi   Author: SecPi   File: alarmdata.py    License: GNU General Public License v3.0 6 votes vote down vote up
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!"} 
Example 7
Project: delocate   Author: matthew-brett   File: tools.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 
Example 8
Project: delocate   Author: matthew-brett   File: tools.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 
Example 9
Project: mealpy   Author: edmundmok   File: venv_update.py    License: MIT License 6 votes vote down vote up
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) 
Example 10
Project: cascade-rcnn_Pytorch   Author: guoruoqian   File: coco.py    License: MIT License 6 votes vote down vote up
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 
Example 11
Project: securityheaders   Author: koenbuyens   File: command_line.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 12
Project: calmjs   Author: calmjs   File: toolchain.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 
Example 13
Project: calmjs   Author: calmjs   File: test_artifact.py    License: GNU General Public License v2.0 6 votes vote down vote up
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)) 
Example 14
Project: calmjs   Author: calmjs   File: test_cli.py    License: GNU General Public License v2.0 6 votes vote down vote up
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",
        }) 
Example 15
Project: calmjs   Author: calmjs   File: test_toolchain.py    License: GNU General Public License v2.0 6 votes vote down vote up
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'])) 
Example 16
Project: calmjs   Author: calmjs   File: test_toolchain.py    License: GNU General Public License v2.0 6 votes vote down vote up
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()) 
Example 17
Project: calmjs   Author: calmjs   File: test_toolchain.py    License: GNU General Public License v2.0 6 votes vote down vote up
def test_transpiler(self):
        # a kind of silly test but shows concept
        tmpdir = mkdtemp(self)
        js_code = 'var dummy = function() {\n};\n'
        source = join(tmpdir, 'source.js')
        target = 'target.js'

        with open(source, 'w') as fd:
            fd.write(js_code)

        spec = Spec(build_dir=tmpdir)
        modname = 'dummy'
        self.toolchain.transpile_modname_source_target(
            spec, modname, source, target)

        with open(join(tmpdir, target)) as fd:
            result = fd.read()

        self.assertEqual(js_code, result)
        self.assertFalse(exists(join(tmpdir, target + '.map'))) 
Example 18
Project: calmjs   Author: calmjs   File: test_npm.py    License: GNU General Public License v2.0 6 votes vote down vote up
def test_view(self):
        stub_mod_call(self, cli)
        tmpdir = mkdtemp(self)
        os.chdir(tmpdir)
        dist = Distribution(dict(
            script_name='setup.py',
            script_args=['npm', '--view'],
            name='foo',
        ))
        dist.parse_command_line()
        dist.run_commands()

        self.assertFalse(exists(join(tmpdir, 'package.json')))
        # also log handlers removed.
        self.assertEqual(len(getLogger('calmjs.cli').handlers), 0)
        # written to stdout with the correct indentation level.
        self.assertIn('\n        "jquery": "~1.11.0"', sys.stdout.getvalue()) 
Example 19
Project: calmjs   Author: calmjs   File: test_npm.py    License: GNU General Public License v2.0 6 votes vote down vote up
def test_install_dryrun(self):
        stub_mod_call(self, cli)
        tmpdir = mkdtemp(self)
        os.chdir(tmpdir)
        dist = Distribution(dict(
            script_name='setup.py',
            script_args=['npm', '--install', '--dry-run'],
            name='foo',
        ))
        dist.parse_command_line()
        dist.run_commands()

        self.assertFalse(exists(join(tmpdir, 'package.json')))
        # Ensure that install is NOT called.
        self.assertIsNone(self.call_args)
        # also log handlers removed.
        self.assertEqual(len(getLogger('calmjs.cli').handlers), 0)
        # However, default action is view, the package.json should be
        # written to stdout with the correct indentation level.
        self.assertIn('\n        "jquery": "~1.11.0"', sys.stdout.getvalue()) 
Example 20
def image_path_from_index(self, index):
    """
    Construct an image path from the image's "index" identifier.
    """
    # Example image path for index=119993:
    #   images/train2014/COCO_train2014_000000119993.jpg
    file_name = ('COCO_' + self._data_name + '_' +
                 str(index).zfill(12) + '.jpg')
    image_path = osp.join(self._data_path, 'images',
                          self._data_name, file_name)
    assert osp.exists(image_path), \
      'Path does not exist: {}'.format(image_path)
    return image_path 
Example 21
Project: mmdetection   Author: open-mmlab   File: test_config.py    License: Apache License 2.0 5 votes vote down vote up
def _get_config_directory():
    """Find the predefined detector config directory."""
    try:
        # Assume we are running in the source mmdetection repo
        repo_dpath = dirname(dirname(__file__))
    except NameError:
        # For IPython development when this __file__ is not defined
        import mmdet
        repo_dpath = dirname(dirname(mmdet.__file__))
    config_dpath = join(repo_dpath, 'configs')
    if not exists(config_dpath):
        raise Exception('Cannot find config path')
    return config_dpath 
Example 22
Project: mmdetection   Author: open-mmlab   File: test_forward.py    License: Apache License 2.0 5 votes vote down vote up
def _get_config_directory():
    """Find the predefined detector config directory."""
    try:
        # Assume we are running in the source mmdetection repo
        repo_dpath = dirname(dirname(dirname(__file__)))
    except NameError:
        # For IPython development when this __file__ is not defined
        import mmdet
        repo_dpath = dirname(dirname(mmdet.__file__))
    config_dpath = join(repo_dpath, 'configs')
    if not exists(config_dpath):
        raise Exception('Cannot find config path')
    return config_dpath 
Example 23
Project: mmdetection   Author: open-mmlab   File: setup.py    License: Apache License 2.0 5 votes vote down vote up
def get_hash():
    if os.path.exists('.git'):
        sha = get_git_hash()[:7]
    elif os.path.exists(version_file):
        try:
            from mmdet.version import __version__
            sha = __version__.split('+')[-1]
        except ImportError:
            raise ImportError('Unable to get git version')
    else:
        sha = 'unknown'

    return sha 
Example 24
Project: grlc   Author: CLARIAH   File: fileLoaders.py    License: MIT License 5 votes vote down vote up
def getTextForName(self, query_name):
        """Return the query text and query type for the given query name.
        Note that file extention is not part of the query name. For example,
        for `query_name='query1'` would return the content of file `query1.rq`
        from the loader's source (assuming such file exists)."""
        # The URIs of all candidates
        rq_name = query_name + '.rq'
        sparql_name = query_name + '.sparql'
        tpf_name = query_name + '.tpf'
        json_name = query_name + '.json'
        candidates = [
            (rq_name, qType['SPARQL']),
            (sparql_name, qType['SPARQL']),
            (tpf_name, qType['TPF']),
            (json_name, qType['JSON'])
        ]

        for queryFullName, queryType in candidates:
            queryText = self._getText(queryFullName)
            if queryText:
                if (queryType == qType['JSON']):
                    queryText = json.loads(queryText)
                    if 'proto' not in queryText and '@graph' not in queryText:
                        continue
                return queryText, queryType
        # No query found...
        return '', None 
Example 25
Project: grlc   Author: CLARIAH   File: fileLoaders.py    License: MIT License 5 votes vote down vote up
def getLicenceURL(self):
        """Returns the URL of the license file in this repository if one exists."""
        for f in self.fetchFiles():
            if f['name'].lower() == 'license' or f['name'].lower() == 'licence':
                return f['download_url']
        return None 
Example 26
Project: grlc   Author: CLARIAH   File: fileLoaders.py    License: MIT License 5 votes vote down vote up
def _getText(self, filename):
        """Return the content of the specified file contained in the local repo."""
        targetFile = path.join(self.baseDir, filename)
        if path.exists(targetFile):
            with open(targetFile, 'r') as f:
                lines = f.readlines()
                text = ''.join(lines)
                return text
        else:
            return None 
Example 27
Project: spleeter   Author: deezer   File: evaluate.py    License: MIT License 5 votes vote down vote up
def entrypoint(arguments, params):
    """ Command entrypoint.

    :param arguments: Command line parsed argument as argparse.Namespace.
    :param params: Deserialized JSON configuration file provided in CLI args.
    """
    # Parse and check musdb directory.
    musdb_root_directory = arguments.mus_dir
    if not exists(musdb_root_directory):
        raise IOError(f'musdb directory {musdb_root_directory} not found')
    # Separate musdb sources.
    audio_output_directory = _separate_evaluation_dataset(
        arguments,
        musdb_root_directory,
        params)
    # Compute metrics with musdb.
    metrics_output_directory = _compute_musdb_metrics(
        arguments,
        musdb_root_directory,
        audio_output_directory)
    # Compute and pretty print median metrics.
    metrics = _compile_metrics(metrics_output_directory)
    for instrument, metric in metrics.items():
        get_logger().info('%s:', instrument)
        for metric, value in metric.items():
            get_logger().info('%s: %s', metric, f'{np.median(value):.3f}')

    return metrics 
Example 28
Project: spleeter   Author: deezer   File: test_separator.py    License: MIT License 5 votes vote down vote up
def test_separate_to_file(test_file, configuration, backend):
    """ Test file based separation. """
    with tf.Session() as sess:
        instruments = MODEL_TO_INST[configuration]
        separator = Separator(configuration, stft_backend=backend)
        name = splitext(basename(test_file))[0]
        with TemporaryDirectory() as directory:
            separator.separate_to_file(
                test_file,
                directory)
            for instrument in instruments:
                assert exists(join(
                    directory,
                    '{}/{}.wav'.format(name, instrument))) 
Example 29
Project: SecPi   Author: SecPi   File: alarmdata.py    License: GNU General Public License v3.0 5 votes vote down vote up
def show_img(self, name, mimetype):
		fp = path.join(self.datapath, name)
		if(path.exists(fp)):
			return serve_file(fp, mimetype, name)
		else:
			tmpl = self.lookup.get_template("404.mako")
			cherrypy.response.status = 404
			return tmpl.render(page_title="File not found!") 
Example 30
Project: SecPi   Author: SecPi   File: alarmdata.py    License: GNU General Public License v3.0 5 votes vote down vote up
def download(self, name):
		fp = path.join(self.datapath, name)
		if(path.exists(fp)):
			return serve_file(fp, "application/x-download", "attachment")
		else:
			tmpl = self.lookup.get_template("404.mako")
			cherrypy.response.status = 404
			return tmpl.render(page_title="File not found!") 
Example 31
Project: soccer-matlab   Author: utra-robosoccer   File: logz.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def configure_output_dir(d=None):
    """
    Set output directory to d, or to /tmp/somerandomnumber if d is None
    """
    G.first_row = True
    G.log_headers = []
    G.log_current_row = {}
    
    G.output_dir = d or "/tmp/experiments/%i"%int(time.time())
    if not osp.exists(G.output_dir):
        os.makedirs(G.output_dir)
    G.output_file = open(osp.join(G.output_dir, "log.txt"), 'w')
    atexit.register(G.output_file.close)
    print(colorize("Logging data to %s"%G.output_file.name, 'green', bold=True)) 
Example 32
Project: delocate   Author: matthew-brett   File: tools.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_archs(libname):
    """ Return architecture types from library `libname`

    Parameters
    ----------
    libname : str
        filename of binary for which to return arch codes

    Returns
    -------
    arch_names : frozenset
        Empty (frozen)set if no arch codes.  If not empty, contains one or more
        of 'ppc', 'ppc64', 'i386', 'x86_64'
    """
    if not exists(libname):
        raise RuntimeError(libname + " is not a file")
    try:
        stdout = back_tick(['lipo', '-info', libname])
    except RuntimeError:
        return frozenset()
    lines = [line.strip() for line in stdout.split('\n') if line.strip()]
    # For some reason, output from lipo -info on .a file generates this line
    if lines[0] == "input file {0} is not a fat file".format(libname):
        line = lines[1]
    else:
        assert len(lines) == 1
        line = lines[0]
    for reggie in (
            'Non-fat file: {0} is architecture: (.*)'.format(libname),
            'Architectures in the fat file: {0} are: (.*)'.format(libname)):
        reggie = re.compile(reggie)
        match = reggie.match(line)
        if match is not None:
            return frozenset(match.groups()[0].split(' '))
    raise ValueError("Unexpected output: '{0}' for {1}".format(
        stdout, libname)) 
Example 33
Project: delocate   Author: matthew-brett   File: test_wheeltools.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_rewrite_record():
    dist_info_sdir = 'fakepkg2-1.0.dist-info'
    with InTemporaryDirectory():
        zip2dir(PURE_WHEEL, 'wheel')
        record_fname = pjoin('wheel', dist_info_sdir, 'RECORD')
        with open_readable(record_fname, 'rt') as fobj:
            record_orig = fobj.read()
        # Test we get the same record by rewriting
        os.unlink(record_fname)
        rewrite_record('wheel')
        with open_readable(record_fname, 'rt') as fobj:
            record_new = fobj.read()
        assert_record_equal(record_orig, record_new)
        # Test that signature gets deleted
        sig_fname = pjoin('wheel', dist_info_sdir, 'RECORD.jws')
        with open(sig_fname, 'wt') as fobj:
            fobj.write('something')
        rewrite_record('wheel')
        with open_readable(record_fname, 'rt') as fobj:
            record_new = fobj.read()
        assert_record_equal(record_orig, record_new)
        assert_false(exists(sig_fname))
        # Test error for too many dist-infos
        shutil.copytree(pjoin('wheel', dist_info_sdir),
                        pjoin('wheel', 'anotherpkg-2.0.dist-info'))
        assert_raises(WheelToolsError, rewrite_record, 'wheel') 
Example 34
Project: bioservices   Author: cokelaer   File: test_bigg.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_download(bigg):
    with pytest.raises(TypeError):
        bigg.download("iND750", format_="foobar")

    with TempFile() as f:
        bigg.download("iND750", target=f.name)

        assert osp.exists(f.name) 
Example 35
Project: cs294-112_hws   Author: xuwd11   File: logz.py    License: MIT License 5 votes vote down vote up
def configure_output_dir(d=None):
    """
    Set output directory to d, or to /tmp/somerandomnumber if d is None
    """
    G.output_dir = d or "/tmp/experiments/%i"%int(time.time())
    assert not osp.exists(G.output_dir), "Log dir %s already exists! Delete it first or use a different dir"%G.output_dir
    os.makedirs(G.output_dir)
    G.output_file = open(osp.join(G.output_dir, "log.txt"), 'w')
    atexit.register(G.output_file.close)
    print(colorize("Logging data to %s"%G.output_file.name, 'green', bold=True)) 
Example 36
Project: cs294-112_hws   Author: xuwd11   File: logz.py    License: MIT License 5 votes vote down vote up
def configure_output_dir(d=None):
    """
    Set output directory to d, or to /tmp/somerandomnumber if d is None
    """
    G.output_dir = d or "/tmp/experiments/%i"%int(time.time())
    assert not osp.exists(G.output_dir), "Log dir %s already exists! Delete it first or use a different dir"%G.output_dir
    os.makedirs(G.output_dir)
    G.output_file = open(osp.join(G.output_dir, "log.txt"), 'w')
    atexit.register(G.output_file.close)
    print(colorize("Logging data to %s"%G.output_file.name, 'green', bold=True)) 
Example 37
Project: cs294-112_hws   Author: xuwd11   File: logz.py    License: MIT License 5 votes vote down vote up
def configure_output_dir(d=None):
    """
    Set output directory to d, or to /tmp/somerandomnumber if d is None
    """
    G.output_dir = d or "/tmp/experiments/%i"%int(time.time())
    assert not osp.exists(G.output_dir), "Log dir %s already exists! Delete it first or use a different dir"%G.output_dir
    os.makedirs(G.output_dir)
    G.output_file = open(osp.join(G.output_dir, "log.txt"), 'w')
    atexit.register(G.output_file.close)
    print(colorize("Logging data to %s"%G.output_file.name, 'green', bold=True)) 
Example 38
Project: cs294-112_hws   Author: xuwd11   File: logz.py    License: MIT License 5 votes vote down vote up
def configure_output_dir(d=None):
    """
    Set output directory to d, or to /tmp/somerandomnumber if d is None
    """
    G.output_dir = d or "/tmp/experiments/%i"%int(time.time())
    assert not osp.exists(G.output_dir), "Log dir %s already exists! Delete it first or use a different dir"%G.output_dir
    os.makedirs(G.output_dir)
    G.output_file = open(osp.join(G.output_dir, "log.txt"), 'w')
    atexit.register(G.output_file.close)
    print(colorize("Logging data to %s"%G.output_file.name, 'green', bold=True)) 
Example 39
Project: cs294-112_hws   Author: xuwd11   File: logz.py    License: MIT License 5 votes vote down vote up
def configure_output_dir(d=None):
    """
    Set output directory to d, or to /tmp/somerandomnumber if d is None
    """
    G.output_dir = d or "/tmp/experiments/%i"%int(time.time())
    assert not osp.exists(G.output_dir), "Log dir %s already exists! Delete it first or use a different dir"%G.output_dir
    os.makedirs(G.output_dir)
    G.output_file = open(osp.join(G.output_dir, "log.txt"), 'w')
    atexit.register(G.output_file.close)
    print(colorize("Logging data to %s"%G.output_file.name, 'green', bold=True)) 
Example 40
Project: b1tifi   Author: mh4x0f   File: b1tifi.py    License: MIT License 5 votes vote down vote up
def main():
    folderDB = path.expanduser('~/.b1tifi-db')
    db_path = path.join(folderDB, 'b1tifi.db')
    if not path.exists(folderDB):
        mkdir(folderDB)
    shell = Console(db_path)
    shell.cmdloop(banner(version,author))