Python os.path.dirname() Examples

The following are code examples for showing how to use os.path.dirname(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: hydrus   Author: HTTP-APIs   File: test_pep8.py    MIT License 6 votes vote down vote up
def test_pep8(self):
        """Test method to check PEP8 compliance over the entire project."""
        self.file_structure = dirname(dirname(abspath(__file__)))
        print("Testing for PEP8 compliance of python files in {}".format(
            self.file_structure))
        style = pep8.StyleGuide()
        style.options.max_line_length = 100  # Set this to desired maximum line length
        filenames = []
        # Set this to desired folder location
        for root, _, files in os.walk(self.file_structure):
            python_files = [f for f in files if f.endswith(
                '.py') and "examples" not in root]
            for file in python_files:
                if len(root.split('samples')) != 2:     # Ignore samples directory
                    filename = '{0}/{1}'.format(root, file)
                    filenames.append(filename)
        check = style.check_files(filenames)
        self.assertEqual(check.total_errors, 0, 'PEP8 style errors: %d' %
                         check.total_errors) 
Example 2
Project: mmdetection   Author: open-mmlab   File: test_sampler.py    Apache License 2.0 6 votes vote down vote up
def _context_for_ohem():
    try:
        from test_forward import _get_detector_cfg
    except ImportError:
        # Hack: grab testing utils from test_forward to make a context for ohem
        import sys
        from os.path import dirname
        sys.path.insert(0, dirname(__file__))
        from test_forward import _get_detector_cfg
    model, train_cfg, test_cfg = _get_detector_cfg(
        'faster_rcnn_ohem_r50_fpn_1x.py')
    model['pretrained'] = None
    # torchvision roi align supports CPU
    model['bbox_roi_extractor']['roi_layer']['use_torchvision'] = True
    from mmdet.models import build_detector
    context = build_detector(model, train_cfg=train_cfg, test_cfg=test_cfg)
    return context 
Example 3
Project: flasky   Author: RoseOu   File: _compat.py    MIT License 6 votes vote down vote up
def _check_if_pyc(fname):
    """Return True if the extension is .pyc, False if .py
    and None if otherwise"""
    from imp import find_module
    from os.path import realpath, dirname, basename, splitext

    # Normalize the file-path for the find_module()
    filepath = realpath(fname)
    dirpath = dirname(filepath)
    module_name = splitext(basename(filepath))[0]

    # Validate and fetch
    try:
        fileobj, fullpath, (_, _, pytype) = find_module(module_name, [dirpath])
    except ImportError:
        raise IOError("Cannot find config file. "
                      "Path maybe incorrect! : {0}".format(filepath))
    return pytype, fileobj, fullpath 
Example 4
Project: praktipy   Author: The-Ludwig   File: praktiplot.py    MIT License 6 votes vote down vote up
def pretty():  
    try:
        locale.setlocale(locale.LC_ALL, locale_strings[platform.system()])
    except locale.Error:
        print("Could not set the language settings! 3.5 will not be written as 3,5! SO SAD!")

    matplotlib.rcParams.update({
        'font.family': 'serif',
        'text.usetex': True,
        'pgf.rcfonts': False,
        'pgf.texsystem': 'lualatex',
        'pgf.preamble': r'\input{'+dirname(abspath(__file__)).replace(" ", r"\ ")+r'//matplotlib_header.tex'+r'}',
        'axes.formatter.use_locale' : True,
    })

# Currently not working
# if platform.system() == "Windows":
#     plt.style.use('file:\\' + os.path.dirname(os.path.abspath(__file__)) + os.sep + 'praktipy.mplstyle')
# else:
#     plt.style.use('file://' + os.path.dirname(os.path.abspath(__file__)) + os.sep + 'praktipy.mplstyle')

# print('file://' + os.path.dirname(os.path.abspath(__file__)) + os.sep + 'praktipy.mplstyle')
# convenience functions 
Example 5
Project: mealpy   Author: edmundmok   File: venv_update.py    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 6
Project: specio   Author: paris-saclay-cds   File: path.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def load_fsm_path():
    """Return the path to the FSM toy file.

    Parameters
    ----------
    None

    Returns
    -------
    path_data : str
        The path to the FSM data.

    Examples
    --------
    >>> from specio.datasets import load_fsm_path
    >>> load_fsm_path() # doctest: +ELLIPSIS
    '...spectra.fsm'

    """
    module_path = dirname(__file__)
    return join(module_path, 'data', 'spectra.fsm') 
Example 7
Project: specio   Author: paris-saclay-cds   File: path.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def load_sp_path():
    """Return the path to the SP toy file.

    Parameters
    ----------
    None

    Returns
    -------
    path_data : str
        The path to the SPC data.

    Examples
    --------
    >>> from specio.datasets import load_spc_path
    >>> load_sp_path() # doctest: +ELLIPSIS
    '...spectra.sp'

    """
    module_path = dirname(__file__)
    return join(module_path, 'data', 'spectra.sp') 
Example 8
Project: specio   Author: paris-saclay-cds   File: path.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def load_spc_path():
    """Return the path to the SPC toy file.

    Parameters
    ----------
    None

    Returns
    -------
    path_data : str
        The path to the SPC data.

    Examples
    --------
    >>> from specio.datasets import load_spc_path
    >>> load_spc_path() # doctest: +ELLIPSIS
    '...spectra.spc'

    """
    module_path = dirname(__file__)
    return join(module_path, 'data', 'spectra.spc') 
Example 9
Project: specio   Author: paris-saclay-cds   File: path.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def load_mzml_path():
    """Return the path to the mzML toy file.

    Parameters
    ----------
    None

    Returns
    -------
    path_data : str
        The path to the mzML data.

    Examples
    --------
    >>> from specio.datasets import load_mzml_path
    >>> load_mzml_path() # doctest: +ELLIPSIS
    '...spectra.mzml'

    """
    module_path = dirname(__file__)
    return join(module_path, 'data', 'spectra.mzml') 
Example 10
Project: specio   Author: paris-saclay-cds   File: path.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def load_csv_path():
    """Return the path to the CSV toy file.

    Parameters
    ----------
    None

    Returns
    -------
    path_data : str
        The path to the CSV data.

    Examples
    --------
    >>> from specio.datasets import load_csv_path
    >>> load_csv_path() # doctest: +ELLIPSIS
    '...spectra.csv'

    """
    module_path = dirname(__file__)
    return join(module_path, 'data', 'spectra.csv') 
Example 11
Project: calmjs   Author: calmjs   File: toolchain.py    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 12
Project: calmjs   Author: calmjs   File: test_artifact.py    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 13
Project: rowgenerators   Author: Metatab   File: s3.py    MIT License 6 votes vote down vote up
def join_dir(self, s):

        from rowgenerators.appurl import parse_app_url
        from rowgenerators.appurl.util import file_ext
        from os.path import basename, join, dirname
        import pathlib

        try:
            path = s.path
        except AttributeError:
            path = parse_app_url(s).path

        # If there is a netloc, it's an absolute URL
        if s.netloc:
            return s

        new_key = str(pathlib.PurePosixPath(dirname(self.key)).joinpath(path))

        return parse_app_url('s3://{bucket}/{key}'.format(bucket=self.bucket_name.strip('/'), key=new_key.lstrip('/'))) 
Example 14
Project: invenio-openaire   Author: inveniosoftware   File: test_cli.py    MIT License 5 votes vote down vote up
def test_loadfunders(script_info, es):
    """Test CLI for loading grants."""
    assert PersistentIdentifier.query.count() == 0
    runner = CliRunner()
    result = runner.invoke(
        openaire,
        ['loadfunders', '--source',
         join(dirname(__file__), 'testdata/fundref_test.rdf')],
        obj=script_info)
    assert result.exit_code == 0
    assert PersistentIdentifier.query.count() == 6 
Example 15
Project: invenio-openaire   Author: inveniosoftware   File: test_cli.py    MIT License 5 votes vote down vote up
def test_loadgrants(script_info, es, funders):
    """Test CLI for loading grants."""
    # Funders only
    assert PersistentIdentifier.query.count() == 6
    runner = CliRunner()
    result = runner.invoke(
        openaire,
        ['loadgrants', '--source',
         join(dirname(__file__), 'testdata/openaire_test.sqlite')],
        obj=script_info)
    print(result.output)
    assert result.exit_code == 0
    assert PersistentIdentifier.query.count() == 46 
Example 16
Project: invenio-openaire   Author: inveniosoftware   File: conftest.py    MIT License 5 votes vote down vote up
def __init__(self, source):
        """Initialize the harvester."""
        self.source = source
        fname = join(dirname(__file__), 'testdata/mock_oai_pmh.txt')
        with open(fname, 'r') as f:
            self.data = f.readlines() 
Example 17
Project: rhodonite   Author: nestauk   File: setup.py    MIT License 5 votes vote down vote up
def read(*names, **kwargs):
    return io.open(
        join(dirname(__file__), *names),
        encoding=kwargs.get('encoding', 'utf8')
    ).read() 
Example 18
Project: pyblish-win   Author: pyblish   File: test_email_torture.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def openfile(filename):
    from os.path import join, dirname, abspath
    path = abspath(join(dirname(testfile), os.pardir, 'moredata', filename))
    return open(path, 'r')

# Prevent this test from running in the Python distro 
Example 19
Project: pyblish-win   Author: pyblish   File: fix_import.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def probably_a_local_import(self, imp_name):
        if imp_name.startswith(u"."):
            # Relative imports are certainly not local imports.
            return False
        imp_name = imp_name.split(u".", 1)[0]
        base_path = dirname(self.filename)
        base_path = join(base_path, imp_name)
        # If there is no __init__.py next to the file its not in a package
        # so can't be a relative import.
        if not exists(join(dirname(base_path), "__init__.py")):
            return False
        for ext in [".py", sep, ".pyc", ".so", ".sl", ".pyd"]:
            if exists(base_path + ext):
                return True
        return False 
Example 20
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def load_tests(loader, standard_tests, pattern):
    this_dir = dirname(__file__)
    top_dir = dirname(dirname(this_dir))
    package_tests = loader.discover(start_dir=this_dir, pattern='test*.py',
                                    top_level_dir=top_dir)
    standard_tests.addTests(package_tests)
    return standard_tests 
Example 21
Project: pyblish-win   Author: pyblish   File: PyShell.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def prepend_syspath(self, filename):
        "Prepend sys.path with file's directory if not already included"
        self.runcommand("""if 1:
            _filename = %r
            import sys as _sys
            from os.path import dirname as _dirname
            _dir = _dirname(_filename)
            if not _dir in _sys.path:
                _sys.path.insert(0, _dir)
            del _filename, _sys, _dirname, _dir
            \n""" % (filename,)) 
Example 22
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def get_resource(self, request, filename):
        """Return a static resource from the shared folder."""
        filename = join(dirname(__file__), 'shared', basename(filename))
        if isfile(filename):
            mimetype = mimetypes.guess_type(filename)[0] \
                or 'application/octet-stream'
            f = open(filename, 'rb')
            try:
                return Response(f.read(), mimetype=mimetype)
            finally:
                f.close()
        return Response('Not Found', status=404) 
Example 23
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def get_resource(self, request, filename):
        """Return a static resource from the shared folder."""
        filename = join(dirname(__file__), 'shared', basename(filename))
        if isfile(filename):
            mimetype = mimetypes.guess_type(filename)[0] \
                or 'application/octet-stream'
            f = open(filename, 'rb')
            try:
                return Response(f.read(), mimetype=mimetype)
            finally:
                f.close()
        return Response('Not Found', status=404) 
Example 24
Project: py-compose   Author: joaorafaelm   File: configuration.py    MIT License 5 votes vote down vote up
def __init__(
            self, config_file=CONFIG_FILENAME, extensions=SUPORTED_EXTENSIONS
    ):
        if self.exists(config_file, extensions):
            self.config = self._parse()
            self._cast_services()

            # If a custom file is specified, changes the working dir.
            exec_dir = dirname(config_file)
            if exec_dir:
                chdir(exec_dir) 
Example 25
Project: DataHack2018   Author: InnovizTech   File: vis_utils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, point_cloud_size):
        format = GeomVertexFormat.getV3c4t2()
        vdata = GeomVertexData('point', format, Geom.UHDynamic)
        self._pos_writer = GeomVertexWriter(vdata, 'vertex')
        self._color_writer = GeomVertexWriter(vdata, 'color')
        self._tex_writer = GeomVertexWriter(vdata, 'texcoord')
        self._point_cloud_size = point_cloud_size
        self._prev_point_cloud_size = 0

        assert point_cloud_size > 0
        vdata.setNumRows(point_cloud_size * 6)
        self._tex_writer.set_row(0)
        set_texture(self._tex_writer, point_cloud_size)
        pnts = GeomTriangles(Geom.UHStatic)
        pnts.addConsecutiveVertices(0, 3 * 2 * point_cloud_size)
        pnts.closePrimitive()
        points_geom = Geom(vdata)
        points_geom.addPrimitive(pnts)
        snode = GeomNode('points')
        snode.addGeom(points_geom)
        dir_name = osp.dirname(__file__)
        # print(osp.join(dir_name, 'pnts_vs.glsl'))
        vs_shader = osp.join(dir_name, 'pnts_vs.glsl')
        fs_shader = osp.join(dir_name, 'pnts_fs.glsl')
        myShader = Shader.load(Shader.SL_GLSL, vertex=Filename.fromOsSpecific(vs_shader).getFullpath(),
                               fragment=Filename.fromOsSpecific(fs_shader).getFullpath())

        assert myShader is not None
        self.points_node = base.render.attachNewNode(snode)
        self.points_node.setPos(0., 0., 0.)
        self.points_node.set_shader(myShader)
        self.points_node.set_shader_input("view_size", (base.win.getXSize(), base.win.getYSize()))
        self.points_node.node().setBounds(BoundingBox((-1000., -1000., -1000.), (1000., 1000., 1000.)))
        self.points_node.setTransparency(TransparencyAttrib.MAlpha) 
Example 26
Project: rpm2swidtag   Author: swidtags   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def resolve_path(base, target):
	return normpath(join(dirname(base), target)) 
Example 27
Project: rpm2swidtag   Author: swidtags   File: repodata.py    Apache License 2.0 5 votes vote down vote up
def save(self):
		outpath = NamedTemporaryFile(dir=path.dirname(self.path), prefix="." + path.basename(self.path), delete=False)
		self.xml.write(outpath.file, xml_declaration=True, encoding="utf-8", pretty_print=True)
		orig_umask = umask(0)
		umask(orig_umask)
		chmod(outpath.name, 0o666 & ~orig_umask)
		rename(outpath.name, self.path) 
Example 28
Project: reroils-data-legacy   Author: rero   File: test_examples_app.py    GNU General Public License v2.0 5 votes vote down vote up
def example_app():
    """Example app fixture."""
    current_dir = os.getcwd()

    # Go to example directory
    project_dir = dirname(dirname(abspath(__file__)))
    exampleapp_dir = join(project_dir, 'examples')
    os.chdir(exampleapp_dir)

    # Setup application
    assert subprocess.call('./app-setup.sh', shell=True) == 0

    # Setup fixtures
    assert subprocess.call('./app-fixtures.sh', shell=True) == 0

    # Start example app
    webapp = subprocess.Popen(
        'FLASK_APP=app.py flask run --debugger -p 5001',
        stdout=subprocess.PIPE, preexec_fn=os.setsid, shell=True)
    time.sleep(10)
    yield webapp

    # Stop server
    os.killpg(webapp.pid, signal.SIGTERM)

    # Tear down example app
    subprocess.call('./app-teardown.sh', shell=True)

    # Return to the original directory
    os.chdir(current_dir)


# def test_example_app_role_admin(example_app):
#     """Test example app."""
#     cmd = 'curl http://0.0.0.0:5001/'
#     output = subprocess.check_output(cmd, shell=True)
#     assert b'Welcome to REROILS-DATA' in output 
Example 29
Project: mmdetection   Author: open-mmlab   File: test_config.py    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 30
Project: mmdetection   Author: open-mmlab   File: test_forward.py    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 31
Project: NiBetaSeries   Author: HBClab   File: bids.py    MIT License 5 votes vote down vote up
def _run_interface(self, runtime):
        import json
        import os.path as op
        import pkg_resources
        from bids.layout import parse_file_entities
        from bids.layout.writing import build_path

        deriv_cfg = pkg_resources.resource_string("nibetaseries",
                                                  op.join("data", "derivatives.json"))
        deriv_patterns = json.loads(deriv_cfg.decode('utf-8'))['fmriprep_path_patterns']

        subject_entities = parse_file_entities(self.inputs.source_file)
        betaseries_entities = parse_file_entities(self.inputs.in_file)
        # hotfix
        betaseries_entities['description'] = betaseries_entities['desc']

        subject_entities.update(betaseries_entities)

        out_file = build_path(subject_entities, deriv_patterns)

        if not out_file:
            raise ValueError("the provided entities do not make a valid file")

        base_directory = runtime.cwd
        if isdefined(self.inputs.base_directory):
            base_directory = os.path.abspath(self.inputs.base_directory)

        out_path = op.join(base_directory, self.out_path_base, out_file)

        os.makedirs(op.dirname(out_path), exist_ok=True)

        # copy the file to the output directory
        copy(self.inputs.in_file, out_path)

        self._results['out_file'] = out_path

        return runtime 
Example 32
Project: NiBetaSeries   Author: HBClab   File: conftest.py    MIT License 5 votes vote down vote up
def sub_bids(bids_dir, example_file=bids_bold_fname):
    sub_dir = op.dirname(example_file)

    return bids_dir.ensure(sub_dir,
                           dir=True) 
Example 33
Project: NiBetaSeries   Author: HBClab   File: conftest.py    MIT License 5 votes vote down vote up
def sub_fmriprep(deriv_dir, example_file=deriv_bold_fname):
    sub_dir = op.dirname(example_file)

    return deriv_dir.ensure(sub_dir,
                            dir=True) 
Example 34
Project: spqrel_tools   Author: LCAS   File: map_bridge.py    MIT License 5 votes vote down vote up
def __init__(self, memory_service, mapprops, topomap):

        self.memory_service = memory_service

        self.props = self.read_map_properties(mapprops)

        self.mapprops_path = realpath(dirname(mapprops))
        imgpath = join(self.mapprops_path, self.props['image'])

        self.map_img = Image.open(imgpath) 
Example 35
Project: flasky   Author: RoseOu   File: __init__.py    MIT License 5 votes vote down vote up
def get_resource(self, request, filename):
        """Return a static resource from the shared folder."""
        filename = join(dirname(__file__), 'shared', basename(filename))
        if isfile(filename):
            mimetype = mimetypes.guess_type(filename)[0] \
                or 'application/octet-stream'
            f = open(filename, 'rb')
            try:
                return Response(f.read(), mimetype=mimetype)
            finally:
                f.close()
        return Response('Not Found', status=404) 
Example 36
Project: tvdbsimple   Author: phate89   File: setup.py    GNU General Public License v3.0 5 votes vote down vote up
def read(fname):

    here = path.join(path.abspath(path.dirname(__file__)), fname)
    txt = ''
    if (path.isfile(here)):
        # Get the long description from the README file
        with open(here, encoding='utf-8') as f:
            txt= f.read()
    return txt 
Example 37
Project: A.L.F.R.E.D-The-Humanoid   Author: AyushDhanai1419   File: snowboydetect.py    MIT License 5 votes vote down vote up
def swig_import_helper():
        from os.path import dirname
        import imp
        fp = None
        try:
            fp, pathname, description = imp.find_module('_snowboydetect', [dirname(__file__)])
        except ImportError:
            import _snowboydetect
            return _snowboydetect
        if fp is not None:
            try:
                _mod = imp.load_module('_snowboydetect', fp, pathname, description)
            finally:
                fp.close()
            return _mod 
Example 38
Project: find_forks   Author: frost-nzcr4   File: run.py    MIT License 5 votes vote down vote up
def main():
    """Main function to run as shell script."""
    loader = unittest.TestLoader()
    suite = loader.discover(path.abspath(path.dirname(__file__)), pattern='test_*.py')
    runner = unittest.TextTestRunner(buffer=True)
    runner.run(suite) 
Example 39
Project: praktipy   Author: The-Ludwig   File: praktiplot.py    MIT License 5 votes vote down vote up
def fast():
    matplotlib.rcParams.update({
        'font.family': 'serif',
        'text.usetex': True,
        'pgf.rcfonts': False,
        'pgf.texsystem': 'pdflatex',
        'pgf.preamble': r'\input{'+dirname(abspath(__file__)).replace(" ", r"\ ")+r'//matplotlib_header_minimal.tex'+r'}'
    }) 
Example 40
Project: MetrixReloaded   Author: Scrounger   File: MetrixReloadedCover.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def findCover(self, path):
		fpath = p1 = p2 = p3 = ""
		name, ext = os_path.splitext(path)
		ext = ext.lower()

		if os_path.isfile(path):
			dir = os_path.dirname(path)
			p1 = name
			p2 = os_path.join(dir, os_path.basename(dir))

		elif os_path.isdir(path):
			if path.lower().endswith("/bdmv"):
				dir = path[:-5]
				if dir.lower().endswith("/brd"): dir = dir[:-4]
			elif path.lower().endswith("video_ts"):
				dir = path[:-9]
				if dir.lower().endswith("/dvd"): dir = dir[:-4]
			else:
				dir = path
				p2 = os_path.join(dir, "folder")

			prtdir, dirname = os_path.split(dir)
			p1 = os_path.join(dir, dirname)
			p3 = os_path.join(prtdir, dirname)

		pathes = (p1, p2, p3)
		for p in pathes:
			for ext in self.exts:
				path = p + ext
				if os_path.exists(path): break
			if os_path.exists(path):
				fpath = path
				break
		return (p1, fpath) 
Example 41
Project: calmjs   Author: calmjs   File: toolchain.py    GNU General Public License v2.0 5 votes vote down vote up
def _generate_transpile_target(self, spec, target):
        # ensure that the target is fully normalized.
        bd_target = join(spec[BUILD_DIR], normpath(target))
        self._validate_build_target(spec, bd_target)
        if not exists(dirname(bd_target)):
            logger.debug("creating dir '%s'", dirname(bd_target))
            makedirs(dirname(bd_target))

        return bd_target 
Example 42
Project: calmjs   Author: calmjs   File: test_artifact.py    GNU General Public License v2.0 5 votes vote down vote up
def test_grandparent_not_removed(self):
        with open(dirname(self.registry.records[('bad', 'bad.js')]), 'w'):
            pass

        with self.assertRaises(ToolchainAbort):
            with pretty_logging(stream=mocks.StringIO()) as stream:
                self.registry.process_package('bad')

        log = stream.getvalue()
        self.assertIn("its dirname does not lead to a directory", log) 
Example 43
Project: calmjs   Author: calmjs   File: artifact.py    GNU General Public License v2.0 5 votes vote down vote up
def setup_export_location(export_target):
    target_dir = dirname(export_target)
    try:
        if not exists(target_dir):
            makedirs(target_dir)
            logger.debug("created '%s' for '%s'", target_dir, export_target)
        elif not isdir(target_dir):
            logger.error(
                "cannot export to '%s' as its dirname does not lead to a "
                "directory", export_target
            )
            return False
        elif isdir(export_target):
            logger.debug(
                "removing existing export target directory at '%s'",
                export_target
            )
            rmtree(export_target)
        elif exists(export_target):
            logger.debug(
                "removing existing export target at '%s'", export_target)
            unlink(export_target)
    except (IOError, OSError) as e:
        logger.error(
            "failed to prepare export location '%s': %s; ensure that any file "
            "permission issues are corrected and/or remove the egg-info "
            "directory for this package before trying again",
            target_dir, e)
        return False

    return True 
Example 44
Project: tri.form   Author: TriOptima   File: views.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def style(request):
    return HttpResponse(open(join(dirname(dirname(dirname(abspath(__file__)))), 'form.css')).read()) 
Example 45
Project: rowgenerators   Author: Metatab   File: web.py    MIT License 5 votes vote down vote up
def dirname(self):
        from os.path import dirname
        return dirname(self.path) 
Example 46
Project: rowgenerators   Author: Metatab   File: s3.py    MIT License 5 votes vote down vote up
def resource_file(self):

        from rowgenerators.appurl import parse_app_url
        from rowgenerators.appurl.util import file_ext
        from os.path import basename, join, dirname

        return basename(self.resource_url) 
Example 47
Project: rowgenerators   Author: Metatab   File: s3.py    MIT License 5 votes vote down vote up
def resource_format(self):

        from rowgenerators.appurl import parse_app_url
        from rowgenerators.appurl.util import file_ext
        from os.path import basename, join, dirname

        if self._resource_format:
            return self._resource_format
        else:
            return file_ext(self.resource_file) 
Example 48
Project: rowgenerators   Author: Metatab   File: file.py    MIT License 5 votes vote down vote up
def dirname(self):
        raise NotImplementedError() 
Example 49
Project: rowgenerators   Author: Metatab   File: file.py    MIT License 5 votes vote down vote up
def dirname(self):
        return self.inner.dirname() 
Example 50
Project: rowgenerators   Author: Metatab   File: file.py    MIT License 5 votes vote down vote up
def dirname(self):
        return dirname(self.fspath)