Python os.path.split() Examples

The following are code examples for showing how to use os.path.split(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: my-first-blog   Author: AnkurBegining   File: __init__.py    (license) View Source Project 8 votes vote down vote up
def _index(self):
        try:
            return self._dirindex
        except AttributeError:
            ind = {}
            for path in self.zipinfo:
                parts = path.split(os.sep)
                while parts:
                    parent = os.sep.join(parts[:-1])
                    if parent in ind:
                        ind[parent].append(parts[-1])
                        break
                    else:
                        ind[parent] = [parts.pop()]
            self._dirindex = ind
            return ind 
Example 2
Project: python-   Author: secondtonone1   File: __init__.py    (license) View Source Project 7 votes vote down vote up
def _by_version_descending(names):
    """
    Given a list of filenames, return them in descending order
    by version number.

    >>> names = 'bar', 'foo', 'Python-2.7.10.egg', 'Python-2.7.2.egg'
    >>> _by_version_descending(names)
    ['Python-2.7.10.egg', 'Python-2.7.2.egg', 'foo', 'bar']
    >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.egg'
    >>> _by_version_descending(names)
    ['Setuptools-1.2.3.egg', 'Setuptools-1.2.3b1.egg']
    >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.post1.egg'
    >>> _by_version_descending(names)
    ['Setuptools-1.2.3.post1.egg', 'Setuptools-1.2.3b1.egg']
    """
    def _by_version(name):
        """
        Parse each component of the filename
        """
        name, ext = os.path.splitext(name)
        parts = itertools.chain(name.split('-'), [ext])
        return [packaging.version.parse(part) for part in parts]

    return sorted(names, key=_by_version, reverse=True) 
Example 3
Project: python-   Author: secondtonone1   File: __init__.py    (license) View Source Project 7 votes vote down vote up
def run_script(self, script_name, namespace):
        script = 'scripts/' + script_name
        if not self.has_metadata(script):
            raise ResolutionError("No script named %r" % script_name)
        script_text = self.get_metadata(script).replace('\r\n', '\n')
        script_text = script_text.replace('\r', '\n')
        script_filename = self._fn(self.egg_info, script)
        namespace['__file__'] = script_filename
        if os.path.exists(script_filename):
            source = open(script_filename).read()
            code = compile(source, script_filename, 'exec')
            exec(code, namespace, namespace)
        else:
            from linecache import cache
            cache[script_filename] = (
                len(script_text), 0, script_text.split('\n'), script_filename
            )
            script_code = compile(script_text, script_filename, 'exec')
            exec(script_code, namespace, namespace) 
Example 4
Project: python-   Author: secondtonone1   File: __init__.py    (license) View Source Project 7 votes vote down vote up
def parse(cls, src, dist=None):
        """Parse a single entry point from string `src`

        Entry point syntax follows the form::

            name = some.module:some.attr [extra1, extra2]

        The entry name and module name are required, but the ``:attrs`` and
        ``[extras]`` parts are optional
        """
        m = cls.pattern.match(src)
        if not m:
            msg = "EntryPoint must be in 'name=module:attrs [extras]' format"
            raise ValueError(msg, src)
        res = m.groupdict()
        extras = cls._parse_extras(res['extras'])
        attrs = res['attr'].split('.') if res['attr'] else ()
        return cls(res['name'], res['module'], attrs, extras, dist) 
Example 5
Project: my-first-blog   Author: AnkurBegining   File: __init__.py    (license) View Source Project 7 votes vote down vote up
def run_script(self, script_name, namespace):
        script = 'scripts/' + script_name
        if not self.has_metadata(script):
            raise ResolutionError("No script named %r" % script_name)
        script_text = self.get_metadata(script).replace('\r\n', '\n')
        script_text = script_text.replace('\r', '\n')
        script_filename = self._fn(self.egg_info, script)
        namespace['__file__'] = script_filename
        if os.path.exists(script_filename):
            source = open(script_filename).read()
            code = compile(source, script_filename, 'exec')
            exec(code, namespace, namespace)
        else:
            from linecache import cache
            cache[script_filename] = (
                len(script_text), 0, script_text.split('\n'), script_filename
            )
            script_code = compile(script_text, script_filename, 'exec')
            exec(script_code, namespace, namespace) 
Example 6
Project: python-   Author: secondtonone1   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def _index(self):
        try:
            return self._dirindex
        except AttributeError:
            ind = {}
            for path in self.zipinfo:
                parts = path.split(os.sep)
                while parts:
                    parent = os.sep.join(parts[:-1])
                    if parent in ind:
                        ind[parent].append(parts[-1])
                        break
                    else:
                        ind[parent] = [parts.pop()]
            self._dirindex = ind
            return ind 
Example 7
Project: python-   Author: secondtonone1   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def parse(cls, src, dist=None):
        """Parse a single entry point from string `src`

        Entry point syntax follows the form::

            name = some.module:some.attr [extra1, extra2]

        The entry name and module name are required, but the ``:attrs`` and
        ``[extras]`` parts are optional
        """
        m = cls.pattern.match(src)
        if not m:
            msg = "EntryPoint must be in 'name=module:attrs [extras]' format"
            raise ValueError(msg, src)
        res = m.groupdict()
        extras = cls._parse_extras(res['extras'])
        attrs = res['attr'].split('.') if res['attr'] else ()
        return cls(res['name'], res['module'], attrs, extras, dist) 
Example 8
Project: python-   Author: secondtonone1   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def _dep_map(self):
        try:
            return self.__dep_map
        except AttributeError:
            dm = self.__dep_map = {None: []}
            for name in 'requires.txt', 'depends.txt':
                for extra, reqs in split_sections(self._get_metadata(name)):
                    if extra:
                        if ':' in extra:
                            extra, marker = extra.split(':', 1)
                            if invalid_marker(marker):
                                # XXX warn
                                reqs = []
                            elif not evaluate_marker(marker):
                                reqs = []
                        extra = safe_extra(extra) or None
                    dm.setdefault(extra, []).extend(parse_requirements(reqs))
            return dm 
Example 9
Project: python-   Author: secondtonone1   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def _index(self):
        try:
            return self._dirindex
        except AttributeError:
            ind = {}
            for path in self.zipinfo:
                parts = path.split(os.sep)
                while parts:
                    parent = os.sep.join(parts[:-1])
                    if parent in ind:
                        ind[parent].append(parts[-1])
                        break
                    else:
                        ind[parent] = [parts.pop()]
            self._dirindex = ind
            return ind 
Example 10
Project: my-first-blog   Author: AnkurBegining   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def parse(cls, src, dist=None):
        """Parse a single entry point from string `src`

        Entry point syntax follows the form::

            name = some.module:some.attr [extra1, extra2]

        The entry name and module name are required, but the ``:attrs`` and
        ``[extras]`` parts are optional
        """
        m = cls.pattern.match(src)
        if not m:
            msg = "EntryPoint must be in 'name=module:attrs [extras]' format"
            raise ValueError(msg, src)
        res = m.groupdict()
        extras = cls._parse_extras(res['extras'])
        attrs = res['attr'].split('.') if res['attr'] else ()
        return cls(res['name'], res['module'], attrs, extras, dist) 
Example 11
Project: my-first-blog   Author: AnkurBegining   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def _dep_map(self):
        try:
            return self.__dep_map
        except AttributeError:
            dm = self.__dep_map = {None: []}
            for name in 'requires.txt', 'depends.txt':
                for extra, reqs in split_sections(self._get_metadata(name)):
                    if extra:
                        if ':' in extra:
                            extra, marker = extra.split(':', 1)
                            if invalid_marker(marker):
                                # XXX warn
                                reqs = []
                            elif not evaluate_marker(marker):
                                reqs = []
                        extra = safe_extra(extra) or None
                    dm.setdefault(extra, []).extend(parse_requirements(reqs))
            return dm 
Example 12
Project: my-first-blog   Author: AnkurBegining   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def run_script(self, script_name, namespace):
        script = 'scripts/' + script_name
        if not self.has_metadata(script):
            raise ResolutionError("No script named %r" % script_name)
        script_text = self.get_metadata(script).replace('\r\n', '\n')
        script_text = script_text.replace('\r', '\n')
        script_filename = self._fn(self.egg_info, script)
        namespace['__file__'] = script_filename
        if os.path.exists(script_filename):
            source = open(script_filename).read()
            code = compile(source, script_filename, 'exec')
            exec(code, namespace, namespace)
        else:
            from linecache import cache
            cache[script_filename] = (
                len(script_text), 0, script_text.split('\n'), script_filename
            )
            script_code = compile(script_text, script_filename, 'exec')
            exec(script_code, namespace, namespace) 
Example 13
Project: my-first-blog   Author: AnkurBegining   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def _index(self):
        try:
            return self._dirindex
        except AttributeError:
            ind = {}
            for path in self.zipinfo:
                parts = path.split(os.sep)
                while parts:
                    parent = os.sep.join(parts[:-1])
                    if parent in ind:
                        ind[parent].append(parts[-1])
                        break
                    else:
                        ind[parent] = [parts.pop()]
            self._dirindex = ind
            return ind 
Example 14
Project: my-first-blog   Author: AnkurBegining   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def parse(cls, src, dist=None):
        """Parse a single entry point from string `src`

        Entry point syntax follows the form::

            name = some.module:some.attr [extra1, extra2]

        The entry name and module name are required, but the ``:attrs`` and
        ``[extras]`` parts are optional
        """
        m = cls.pattern.match(src)
        if not m:
            msg = "EntryPoint must be in 'name=module:attrs [extras]' format"
            raise ValueError(msg, src)
        res = m.groupdict()
        extras = cls._parse_extras(res['extras'])
        attrs = res['attr'].split('.') if res['attr'] else ()
        return cls(res['name'], res['module'], attrs, extras, dist) 
Example 15
Project: sc8pr   Author: dmaccarthy   File: s8vUtil.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def record(self):
        "Begin screen grab recording"
        if self.recFolder is None:
            fldr = TkDialog(FOLDER, initialdir="./").run()
            if fldr: self.recFolder = fldr
            else: return
        try:
            param = TkDialog(str, "Enter recording " +
                "parameters using one of these formats:\n" +
                "fps\nfps w h\nfps x y w h", "Record", initialvalue="15").run()
            param = [int(c) for c in param.split(" ") if c]
            self.frameRate = param[0]
            self.grab = Grabber(param[1:] if len(param) > 1 else None)
            self.rec = []
            vid = self.vid
            if vid is not None:
                self.vid = None
                self -= vid
            self._recordStart = time()
        except: pass # Abort! 
Example 16
Project: sc8pr   Author: dmaccarthy   File: s8vUtil.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def parse(fn):
        """Parse a file name into a pattern; for example...
        'img007.png' --> ('img{:03d}.png', 7)"""
        path, fn = split(fn)
        if not path: path = "."
        ftype = fn.split(".")[-1]
        fn = fn[:-1-len(ftype)]
        n = None
        i = 0
        for c in fn:
            if c in "0123456789":
                n = i
                break
            else: i += 1
        if n is None: return None
        start = int(fn[n:])
        if fn[n] == "0":
            d = len(fn) - n
            fn = fn[:n] + "{:0" + str(d) + "d}." + ftype
        else:
            fn = fn[:n] + "{}." + ftype
        return path + "/" + fn, start 
Example 17
Project: NeoAnalysis   Author: neoanalysis   File: elphyio.py    (license) View Source Project 6 votes vote down vote up
def detect_protocol_from_name(self, path):
        pattern = "\d{4}(\d+|\D)\D"
        codes = {
            'r':'sparsenoise',
            'o':'movingbar',
            'f':'flashbar',
            'm':'multistim' # here just for assertion
        }
        filename = path.split(path)[1]
        match = re.search(pattern, path)
        if hasattr(match, 'end') :
            code = codes.get(path[match.end() - 1].lower(), None)
            assert code != 'm', "multistim file detected"
            return code 
        elif 'spt' in filename.lower() :
            return 'spontaneousactivity'
        else :
            return None 
Example 18
Project: NeoAnalysis   Author: neoanalysis   File: elphyio.py    (license) View Source Project 6 votes vote down vote up
def detect_protocol_from_name(self, path):
        pattern = "\d{4}(\d+|\D)\D"
        codes = {
            'r':'sparsenoise',
            'o':'movingbar',
            'f':'flashbar',
            'm':'multistim' # here just for assertion
        }
        filename = path.split(path)[1]
        match = re.search(pattern, path)
        if hasattr(match, 'end') :
            code = codes.get(path[match.end() - 1].lower(), None)
            assert code != 'm', "multistim file detected"
            return code 
        elif 'spt' in filename.lower() :
            return 'spontaneousactivity'
        else :
            return None 
Example 19
Project: Flask_Blog   Author: sugarguo   File: pkg_resources.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def _macosx_vers(_cache=[]):
    if not _cache:
        import platform
        version = platform.mac_ver()[0]
        # fallback for MacPorts
        if version == '':
            import plistlib
            plist = '/System/Library/CoreServices/SystemVersion.plist'
            if os.path.exists(plist):
                if hasattr(plistlib, 'readPlist'):
                    plist_content = plistlib.readPlist(plist)
                    if 'ProductVersion' in plist_content:
                        version = plist_content['ProductVersion']

        _cache.append(version.split('.'))
    return _cache[0] 
Example 20
Project: Flask_Blog   Author: sugarguo   File: pkg_resources.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def run_script(self,script_name,namespace):
        script = 'scripts/'+script_name
        if not self.has_metadata(script):
            raise ResolutionError("No script named %r" % script_name)
        script_text = self.get_metadata(script).replace('\r\n','\n')
        script_text = script_text.replace('\r','\n')
        script_filename = self._fn(self.egg_info,script)
        namespace['__file__'] = script_filename
        if os.path.exists(script_filename):
            execfile(script_filename, namespace, namespace)
        else:
            from linecache import cache
            cache[script_filename] = (
                len(script_text), 0, script_text.split('\n'), script_filename
            )
            script_code = compile(script_text,script_filename,'exec')
            exec(script_code, namespace, namespace) 
Example 21
Project: Flask_Blog   Author: sugarguo   File: pkg_resources.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def _index(self):
        try:
            return self._dirindex
        except AttributeError:
            ind = {}
            for path in self.zipinfo:
                parts = path.split(os.sep)
                while parts:
                    parent = os.sep.join(parts[:-1])
                    if parent in ind:
                        ind[parent].append(parts[-1])
                        break
                    else:
                        ind[parent] = [parts.pop()]
            self._dirindex = ind
            return ind 
Example 22
Project: Flask_Blog   Author: sugarguo   File: pkg_resources.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def _dep_map(self):
        try:
            return self.__dep_map
        except AttributeError:
            dm = self.__dep_map = {None: []}
            for name in 'requires.txt', 'depends.txt':
                for extra,reqs in split_sections(self._get_metadata(name)):
                    if extra:
                        if ':' in extra:
                            extra, marker = extra.split(':',1)
                            if invalid_marker(marker):
                                reqs=[] # XXX warn
                            elif not evaluate_marker(marker):
                                reqs=[]
                        extra = safe_extra(extra) or None
                    dm.setdefault(extra,[]).extend(parse_requirements(reqs))
            return dm 
Example 23
Project: Flask_Blog   Author: sugarguo   File: pkg_resources.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def _macosx_vers(_cache=[]):
    if not _cache:
        import platform
        version = platform.mac_ver()[0]
        # fallback for MacPorts
        if version == '':
            import plistlib
            plist = '/System/Library/CoreServices/SystemVersion.plist'
            if os.path.exists(plist):
                if hasattr(plistlib, 'readPlist'):
                    plist_content = plistlib.readPlist(plist)
                    if 'ProductVersion' in plist_content:
                        version = plist_content['ProductVersion']

        _cache.append(version.split('.'))
    return _cache[0] 
Example 24
Project: Flask_Blog   Author: sugarguo   File: pkg_resources.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def _index(self):
        try:
            return self._dirindex
        except AttributeError:
            ind = {}
            for path in self.zipinfo:
                parts = path.split(os.sep)
                while parts:
                    parent = os.sep.join(parts[:-1])
                    if parent in ind:
                        ind[parent].append(parts[-1])
                        break
                    else:
                        ind[parent] = [parts.pop()]
            self._dirindex = ind
            return ind 
Example 25
Project: Flask_Blog   Author: sugarguo   File: pkg_resources.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def _dep_map(self):
        try:
            return self.__dep_map
        except AttributeError:
            dm = self.__dep_map = {None: []}
            for name in 'requires.txt', 'depends.txt':
                for extra,reqs in split_sections(self._get_metadata(name)):
                    if extra:
                        if ':' in extra:
                            extra, marker = extra.split(':',1)
                            if invalid_marker(marker):
                                reqs=[] # XXX warn
                            elif not evaluate_marker(marker):
                                reqs=[]
                        extra = safe_extra(extra) or None
                    dm.setdefault(extra,[]).extend(parse_requirements(reqs))
            return dm 
Example 26
Project: pip-update-requirements   Author: alanhamlett   File: __init__.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def run_script(self, script_name, namespace):
        script = 'scripts/' + script_name
        if not self.has_metadata(script):
            raise ResolutionError("No script named %r" % script_name)
        script_text = self.get_metadata(script).replace('\r\n', '\n')
        script_text = script_text.replace('\r', '\n')
        script_filename = self._fn(self.egg_info, script)
        namespace['__file__'] = script_filename
        if os.path.exists(script_filename):
            source = open(script_filename).read()
            code = compile(source, script_filename, 'exec')
            exec(code, namespace, namespace)
        else:
            from linecache import cache
            cache[script_filename] = (
                len(script_text), 0, script_text.split('\n'), script_filename
            )
            script_code = compile(script_text, script_filename, 'exec')
            exec(script_code, namespace, namespace) 
Example 27
Project: pip-update-requirements   Author: alanhamlett   File: __init__.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def _index(self):
        try:
            return self._dirindex
        except AttributeError:
            ind = {}
            for path in self.zipinfo:
                parts = path.split(os.sep)
                while parts:
                    parent = os.sep.join(parts[:-1])
                    if parent in ind:
                        ind[parent].append(parts[-1])
                        break
                    else:
                        ind[parent] = [parts.pop()]
            self._dirindex = ind
            return ind 
Example 28
Project: pip-update-requirements   Author: alanhamlett   File: __init__.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def _by_version_descending(names):
    """
    Given a list of filenames, return them in descending order
    by version number.

    >>> names = 'bar', 'foo', 'Python-2.7.10.egg', 'Python-2.7.2.egg'
    >>> _by_version_descending(names)
    ['Python-2.7.10.egg', 'Python-2.7.2.egg', 'foo', 'bar']
    >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.egg'
    >>> _by_version_descending(names)
    ['Setuptools-1.2.3.egg', 'Setuptools-1.2.3b1.egg']
    >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.post1.egg'
    >>> _by_version_descending(names)
    ['Setuptools-1.2.3.post1.egg', 'Setuptools-1.2.3b1.egg']
    """
    def _by_version(name):
        """
        Parse each component of the filename
        """
        name, ext = os.path.splitext(name)
        parts = itertools.chain(name.split('-'), [ext])
        return [packaging.version.parse(part) for part in parts]

    return sorted(names, key=_by_version, reverse=True) 
Example 29
Project: pip-update-requirements   Author: alanhamlett   File: __init__.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def parse(cls, src, dist=None):
        """Parse a single entry point from string `src`

        Entry point syntax follows the form::

            name = some.module:some.attr [extra1, extra2]

        The entry name and module name are required, but the ``:attrs`` and
        ``[extras]`` parts are optional
        """
        m = cls.pattern.match(src)
        if not m:
            msg = "EntryPoint must be in 'name=module:attrs [extras]' format"
            raise ValueError(msg, src)
        res = m.groupdict()
        extras = cls._parse_extras(res['extras'])
        attrs = res['attr'].split('.') if res['attr'] else ()
        return cls(res['name'], res['module'], attrs, extras, dist) 
Example 30
Project: pip-update-requirements   Author: alanhamlett   File: __init__.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def _dep_map(self):
        try:
            return self.__dep_map
        except AttributeError:
            dm = self.__dep_map = {None: []}
            for name in 'requires.txt', 'depends.txt':
                for extra, reqs in split_sections(self._get_metadata(name)):
                    if extra:
                        if ':' in extra:
                            extra, marker = extra.split(':', 1)
                            if invalid_marker(marker):
                                # XXX warn
                                reqs = []
                            elif not evaluate_marker(marker):
                                reqs = []
                        extra = safe_extra(extra) or None
                    dm.setdefault(extra, []).extend(parse_requirements(reqs))
            return dm 
Example 31
Project: code   Author: ActiveState   File: recipe-576522.py    (MIT License) View Source Project 6 votes vote down vote up
def which_file(fname):
	"""prints paths for fname where fname can be found,
	in case of .dll loads it"""
	files = []
	path = win32api.GetEnvironmentVariable('PATH')
	# try paths as described in MSDN
	dirs = [os.getcwd(), win32api.GetSystemDirectory(), win32api.GetWindowsDirectory()] + path.split(';')
	dirs_norm = []
	dirs_l = []
	for d in dirs:
		dn = d.lower()
		if dn not in dirs_l:
			dirs_l.append(dn)
			dirs_norm.append(d)
	for d in dirs_norm:
		fname2 = os.path.join(d, fname)
		if os.path.exists(fname2):
			if fname2 not in files:
				files.append(fname2)
	if files:
		print('\n'.join([get_file_info(f) for f in files]))
	h = 0
	if fname.lower().endswith('.dll'):
		print('\ttrying to load "%s" ...' % (fname))
		try:
			h = win32api.LoadLibrary(fname)
			if h:
				dll_name = win32api.GetModuleFileName(h)
				print('\t%s loaded' % (dll_name))
		except:
			print('\tCannot load "%s" !!!' % (fname)) 
Example 32
Project: gdb.vim   Author: dbgx   File: session.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def handle_show(self):
        if self.isalive():
            sfile_bufnr = self.vimx.buffer_add(self.get_confpath())
            self.vimx.command('exe "tab drop ".escape(bufname({0}), "$%# ")'
                              .format(sfile_bufnr))

            json_str = json.dumps(self.state, indent=4, separators=(',', ': '))

            def json_show(b):
                if b.number == sfile_bufnr:
                    b[:] = json_str.split('\n')
                    raise StopIteration

            self.vimx.map_buffers(json_show)
            if self.help_flags["new"] and self.help_flags["session_show"]:
                self.vimx.log(
                    'Save this file, and do `:GGsession reload` to load any changes made.')
                self.help_flags["session_show"] = False
        else:
            self.vimx.log("No active session.") 
Example 33
Project: swjtu-pyscraper   Author: Desgard   File: __init__.py    (MIT License) View Source Project 6 votes vote down vote up
def run_script(self, script_name, namespace):
        script = 'scripts/'+script_name
        if not self.has_metadata(script):
            raise ResolutionError("No script named %r" % script_name)
        script_text = self.get_metadata(script).replace('\r\n', '\n')
        script_text = script_text.replace('\r', '\n')
        script_filename = self._fn(self.egg_info, script)
        namespace['__file__'] = script_filename
        if os.path.exists(script_filename):
            source = open(script_filename).read()
            code = compile(source, script_filename, 'exec')
            exec(code, namespace, namespace)
        else:
            from linecache import cache
            cache[script_filename] = (
                len(script_text), 0, script_text.split('\n'), script_filename
            )
            script_code = compile(script_text, script_filename,'exec')
            exec(script_code, namespace, namespace) 
Example 34
Project: swjtu-pyscraper   Author: Desgard   File: __init__.py    (MIT License) View Source Project 6 votes vote down vote up
def _index(self):
        try:
            return self._dirindex
        except AttributeError:
            ind = {}
            for path in self.zipinfo:
                parts = path.split(os.sep)
                while parts:
                    parent = os.sep.join(parts[:-1])
                    if parent in ind:
                        ind[parent].append(parts[-1])
                        break
                    else:
                        ind[parent] = [parts.pop()]
            self._dirindex = ind
            return ind 
Example 35
Project: swjtu-pyscraper   Author: Desgard   File: __init__.py    (MIT License) View Source Project 6 votes vote down vote up
def _rebuild_mod_path(orig_path, package_name, module):
    """
    Rebuild module.__path__ ensuring that all entries are ordered
    corresponding to their sys.path order
    """
    sys_path = [_normalize_cached(p) for p in sys.path]
    def position_in_sys_path(path):
        """
        Return the ordinal of the path based on its position in sys.path
        """
        path_parts = path.split(os.sep)
        module_parts = package_name.count('.') + 1
        parts = path_parts[:-module_parts]
        return sys_path.index(_normalize_cached(os.sep.join(parts)))

    orig_path.sort(key=position_in_sys_path)
    module.__path__[:] = [_normalize_cached(p) for p in orig_path] 
Example 36
Project: swjtu-pyscraper   Author: Desgard   File: __init__.py    (MIT License) View Source Project 6 votes vote down vote up
def _dep_map(self):
        try:
            return self.__dep_map
        except AttributeError:
            dm = self.__dep_map = {None: []}
            for name in 'requires.txt', 'depends.txt':
                for extra, reqs in split_sections(self._get_metadata(name)):
                    if extra:
                        if ':' in extra:
                            extra, marker = extra.split(':', 1)
                            if invalid_marker(marker):
                                # XXX warn
                                reqs=[]
                            elif not evaluate_marker(marker):
                                reqs=[]
                        extra = safe_extra(extra) or None
                    dm.setdefault(extra,[]).extend(parse_requirements(reqs))
            return dm 
Example 37
Project: swjtu-pyscraper   Author: Desgard   File: __init__.py    (MIT License) View Source Project 6 votes vote down vote up
def _index(self):
        try:
            return self._dirindex
        except AttributeError:
            ind = {}
            for path in self.zipinfo:
                parts = path.split(os.sep)
                while parts:
                    parent = os.sep.join(parts[:-1])
                    if parent in ind:
                        ind[parent].append(parts[-1])
                        break
                    else:
                        ind[parent] = [parts.pop()]
            self._dirindex = ind
            return ind 
Example 38
Project: swjtu-pyscraper   Author: Desgard   File: __init__.py    (MIT License) View Source Project 6 votes vote down vote up
def parse(cls, src, dist=None):
        """Parse a single entry point from string `src`

        Entry point syntax follows the form::

            name = some.module:some.attr [extra1, extra2]

        The entry name and module name are required, but the ``:attrs`` and
        ``[extras]`` parts are optional
        """
        m = cls.pattern.match(src)
        if not m:
            msg = "EntryPoint must be in 'name=module:attrs [extras]' format"
            raise ValueError(msg, src)
        res = m.groupdict()
        extras = cls._parse_extras(res['extras'])
        attrs = res['attr'].split('.') if res['attr'] else ()
        return cls(res['name'], res['module'], attrs, extras, dist) 
Example 39
Project: swjtu-pyscraper   Author: Desgard   File: __init__.py    (MIT License) View Source Project 6 votes vote down vote up
def _dep_map(self):
        try:
            return self.__dep_map
        except AttributeError:
            dm = self.__dep_map = {None: []}
            for name in 'requires.txt', 'depends.txt':
                for extra, reqs in split_sections(self._get_metadata(name)):
                    if extra:
                        if ':' in extra:
                            extra, marker = extra.split(':', 1)
                            if invalid_marker(marker):
                                # XXX warn
                                reqs = []
                            elif not evaluate_marker(marker):
                                reqs = []
                        extra = safe_extra(extra) or None
                    dm.setdefault(extra, []).extend(parse_requirements(reqs))
            return dm 
Example 40
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: __init__.py    (MIT License) View Source Project 6 votes vote down vote up
def run_script(self, script_name, namespace):
        script = 'scripts/'+script_name
        if not self.has_metadata(script):
            raise ResolutionError("No script named %r" % script_name)
        script_text = self.get_metadata(script).replace('\r\n', '\n')
        script_text = script_text.replace('\r', '\n')
        script_filename = self._fn(self.egg_info, script)
        namespace['__file__'] = script_filename
        if os.path.exists(script_filename):
            source = open(script_filename).read()
            code = compile(source, script_filename, 'exec')
            exec(code, namespace, namespace)
        else:
            from linecache import cache
            cache[script_filename] = (
                len(script_text), 0, script_text.split('\n'), script_filename
            )
            script_code = compile(script_text, script_filename,'exec')
            exec(script_code, namespace, namespace) 
Example 41
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: __init__.py    (MIT License) View Source Project 6 votes vote down vote up
def _index(self):
        try:
            return self._dirindex
        except AttributeError:
            ind = {}
            for path in self.zipinfo:
                parts = path.split(os.sep)
                while parts:
                    parent = os.sep.join(parts[:-1])
                    if parent in ind:
                        ind[parent].append(parts[-1])
                        break
                    else:
                        ind[parent] = [parts.pop()]
            self._dirindex = ind
            return ind 
Example 42
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: __init__.py    (MIT License) View Source Project 6 votes vote down vote up
def _rebuild_mod_path(orig_path, package_name, module):
    """
    Rebuild module.__path__ ensuring that all entries are ordered
    corresponding to their sys.path order
    """
    sys_path = [_normalize_cached(p) for p in sys.path]
    def position_in_sys_path(path):
        """
        Return the ordinal of the path based on its position in sys.path
        """
        path_parts = path.split(os.sep)
        module_parts = package_name.count('.') + 1
        parts = path_parts[:-module_parts]
        return sys_path.index(_normalize_cached(os.sep.join(parts)))

    orig_path.sort(key=position_in_sys_path)
    module.__path__[:] = [_normalize_cached(p) for p in orig_path] 
Example 43
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: __init__.py    (MIT License) View Source Project 6 votes vote down vote up
def _dep_map(self):
        try:
            return self.__dep_map
        except AttributeError:
            dm = self.__dep_map = {None: []}
            for name in 'requires.txt', 'depends.txt':
                for extra, reqs in split_sections(self._get_metadata(name)):
                    if extra:
                        if ':' in extra:
                            extra, marker = extra.split(':', 1)
                            if invalid_marker(marker):
                                # XXX warn
                                reqs=[]
                            elif not evaluate_marker(marker):
                                reqs=[]
                        extra = safe_extra(extra) or None
                    dm.setdefault(extra,[]).extend(parse_requirements(reqs))
            return dm 
Example 44
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: __init__.py    (MIT License) View Source Project 6 votes vote down vote up
def _index(self):
        try:
            return self._dirindex
        except AttributeError:
            ind = {}
            for path in self.zipinfo:
                parts = path.split(os.sep)
                while parts:
                    parent = os.sep.join(parts[:-1])
                    if parent in ind:
                        ind[parent].append(parts[-1])
                        break
                    else:
                        ind[parent] = [parts.pop()]
            self._dirindex = ind
            return ind 
Example 45
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: __init__.py    (MIT License) View Source Project 6 votes vote down vote up
def parse(cls, src, dist=None):
        """Parse a single entry point from string `src`

        Entry point syntax follows the form::

            name = some.module:some.attr [extra1, extra2]

        The entry name and module name are required, but the ``:attrs`` and
        ``[extras]`` parts are optional
        """
        m = cls.pattern.match(src)
        if not m:
            msg = "EntryPoint must be in 'name=module:attrs [extras]' format"
            raise ValueError(msg, src)
        res = m.groupdict()
        extras = cls._parse_extras(res['extras'])
        attrs = res['attr'].split('.') if res['attr'] else ()
        return cls(res['name'], res['module'], attrs, extras, dist) 
Example 46
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: __init__.py    (MIT License) View Source Project 6 votes vote down vote up
def _dep_map(self):
        try:
            return self.__dep_map
        except AttributeError:
            dm = self.__dep_map = {None: []}
            for name in 'requires.txt', 'depends.txt':
                for extra, reqs in split_sections(self._get_metadata(name)):
                    if extra:
                        if ':' in extra:
                            extra, marker = extra.split(':', 1)
                            if invalid_marker(marker):
                                # XXX warn
                                reqs=[]
                            elif not evaluate_marker(marker):
                                reqs=[]
                        extra = safe_extra(extra) or None
                    dm.setdefault(extra,[]).extend(parse_requirements(reqs))
            return dm 
Example 47
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: __init__.py    (MIT License) View Source Project 6 votes vote down vote up
def run_script(self, script_name, namespace):
        script = 'scripts/'+script_name
        if not self.has_metadata(script):
            raise ResolutionError("No script named %r" % script_name)
        script_text = self.get_metadata(script).replace('\r\n', '\n')
        script_text = script_text.replace('\r', '\n')
        script_filename = self._fn(self.egg_info, script)
        namespace['__file__'] = script_filename
        if os.path.exists(script_filename):
            source = open(script_filename).read()
            code = compile(source, script_filename, 'exec')
            exec(code, namespace, namespace)
        else:
            from linecache import cache
            cache[script_filename] = (
                len(script_text), 0, script_text.split('\n'), script_filename
            )
            script_code = compile(script_text, script_filename,'exec')
            exec(script_code, namespace, namespace) 
Example 48
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: __init__.py    (MIT License) View Source Project 6 votes vote down vote up
def _index(self):
        try:
            return self._dirindex
        except AttributeError:
            ind = {}
            for path in self.zipinfo:
                parts = path.split(os.sep)
                while parts:
                    parent = os.sep.join(parts[:-1])
                    if parent in ind:
                        ind[parent].append(parts[-1])
                        break
                    else:
                        ind[parent] = [parts.pop()]
            self._dirindex = ind
            return ind 
Example 49
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: __init__.py    (MIT License) View Source Project 6 votes vote down vote up
def _rebuild_mod_path(orig_path, package_name, module):
    """
    Rebuild module.__path__ ensuring that all entries are ordered
    corresponding to their sys.path order
    """
    sys_path = [_normalize_cached(p) for p in sys.path]
    def position_in_sys_path(path):
        """
        Return the ordinal of the path based on its position in sys.path
        """
        path_parts = path.split(os.sep)
        module_parts = package_name.count('.') + 1
        parts = path_parts[:-module_parts]
        return sys_path.index(_normalize_cached(os.sep.join(parts)))

    orig_path.sort(key=position_in_sys_path)
    module.__path__[:] = [_normalize_cached(p) for p in orig_path] 
Example 50
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: __init__.py    (MIT License) View Source Project 6 votes vote down vote up
def parse(cls, src, dist=None):
        """Parse a single entry point from string `src`

        Entry point syntax follows the form::

            name = some.module:some.attr [extra1, extra2]

        The entry name and module name are required, but the ``:attrs`` and
        ``[extras]`` parts are optional
        """
        m = cls.pattern.match(src)
        if not m:
            msg = "EntryPoint must be in 'name=module:attrs [extras]' format"
            raise ValueError(msg, src)
        res = m.groupdict()
        extras = cls._parse_extras(res['extras'])
        attrs = res['attr'].split('.') if res['attr'] else ()
        return cls(res['name'], res['module'], attrs, extras, dist)