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


Python builtin.BuiltinRegistry类代码示例

本文整理汇总了Python中hotwire.builtin.BuiltinRegistry的典型用法代码示例。如果您正苦于以下问题:Python BuiltinRegistry类的具体用法?Python BuiltinRegistry怎么用?Python BuiltinRegistry使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了BuiltinRegistry类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: create

    def create(context, resolver, *tokens, **kwargs):
        if context is None:
            context = HotwireContext()
        accept_partial = (('accept_partial' in kwargs) and kwargs['accept_partial'])
        components = []
        undoable = None
        idempotent = True
        prev = None
        pipeline_input_type = 'unknown'
        pipeline_input_optional = 'unknown'
        pipeline_output_type = None
        prev_locality = None
        pipeline_singlevalue = None
        pipeline_type_validates = True
        pushback = []
        tokens = list(tokens)
        def pull_token():
            if pushback:
                return pushback.pop(0)
            else:
                return tokens.pop(0)            
        while tokens or pushback:
            builtin_token = pull_token()
            _logger.debug("token = %r", builtin_token)    
                
            def forcetoken(t):
                # Allow passing plain strings for convenience from Python.
                # Treat them as quoted.
                if isinstance(t, basestring):
                    return ParsedToken(t, -1, quoted=True)
                return t
            
            builtin_token = forcetoken(builtin_token)

            # Attempt to determine which builtin we're using
            if isinstance(builtin_token, Builtin):
                b = builtin_token
                cmdargs = []
            # If we're parsing without a resolver, assume we're using sys
            elif isinstance(builtin_token, ParsedToken):
                try:
                    b = BuiltinRegistry.getInstance()[builtin_token.text]
                    cmdargs = []
                except KeyError, e:
                    if resolver:
                        (b, cmdargs) = resolver.resolve(builtin_token.text, context)
                        _logger.debug("resolved: %r to %r %r", builtin_token.text, b, cmdargs)
                        if not b:
                            raise PipelineParseException(_('No matches for %s') % (gobject.markup_escape_text(builtin_token.text),))
                    else:
                        b = BuiltinRegistry.getInstance()['sys']
                        cmdargs = [ParsedToken(builtin_token.text, builtin_token.start, end=builtin_token.end)]
            elif builtin_token in (hotwire.script.PIPE, hotwire.script.REDIR_IN, hotwire.script.REDIR_OUT, hotwire.script.REDIR_OUT_APPEND):
                raise PipelineParseException(_("Unexpected token %d") % (builtin_token,))
开发者ID:zsx,项目名称:hotwire,代码行数:54,代码来源:command.py

示例2: completions

 def completions(self, text, cwd, context=None):
     for builtin in BuiltinRegistry.getInstance():
         compl = self._match(builtin.name, text, builtin)
         if compl: yield compl
         for alias in builtin.aliases:
             compl = self._match(alias, text, builtin)
             if compl: yield compl
开发者ID:sandeep-datta,项目名称:hotwire,代码行数:7,代码来源:completion.py

示例3: __help_items

 def __help_items(self, items):
     builtins = BuiltinRegistry.getInstance()        
     for name in items:
         builtin = builtins[name]
         self.__append_builtin_base_help(builtin)
         self.__append_builtin_aliases(builtin)
         self.__append_builtin_arghelp(builtin)
         self.__append_builtin_doc(builtin)
开发者ID:zsx,项目名称:hotwire,代码行数:8,代码来源:help.py

示例4: __help_all

    def __help_all(self):
        pbcache = PixbufCache.getInstance()        
        self._buf.insert_markup('Hotwire <i>%s</i>\n\n' % (__version__,))
        self._buf.insert_markup(_('Documentation on the web: '))
        self._buf.insert_markup(' ')
        self.append_link(_('Tutorial'), 'http://code.google.com/p/hotwire-shell/wiki/GettingStarted0700')
        self._buf.insert_markup(' ')
        external_pixbuf = pbcache.get('external.png', size=10)
        self._buf.insert_pixbuf(self._buf.get_end_iter(), external_pixbuf)         
        self._buf.insert_markup('\n\n')

        registry = BuiltinRegistry.getInstance()
        for (setname,builtins) in zip((_('User'), _('Standard'), _('System')), map(list, [registry.user_set, registry.hotwire_set, registry.system_set])):
            if len(builtins) == 0:
                continue 
            self._buf.insert_markup('<larger>%s:</larger>\n' % (_('%s Builtin Commands' % (setname,)),))
            builtins.sort(lambda a,b: cmp(a.name, b.name))
            for builtin in builtins:
                self.__append_builtin_base_help(builtin)
                self.__append_builtin_aliases(builtin)
                self.__append_builtin_arghelp(builtin)            
                self.__append_builtin_doc(builtin)
            self._buf.insert_markup('\n')

        self._buf.insert_markup('<larger>%s:</larger>\n' % (_('Languages'),))
        langreg = PipelineLanguageRegistry.getInstance()
        hotwire_lang = langreg['62270c40-a94a-44dd-aaa0-689f882acf34']
        python_lang = langreg['da3343a0-8bce-46ed-a463-2d17ab09d9b4']
        self.__append_language(hotwire_lang)
        self.__append_language(python_lang) 
        languages = list(langreg)       
        languages.sort(lambda a,b: cmp(a.langname, b.langname))
        for language in languages:
            if language in [hotwire_lang, python_lang]:
                continue
            self.__append_language(language)           
            
        self._buf.insert_markup('\n<larger>%s:</larger>\n' % (_('Aliases'),))
        aliases = list(AliasRegistry.getInstance())
        aliases.sort(lambda a,b: cmp(a.name,b.name))
        for alias in aliases:
            self._buf.insert_markup('  <b>%s</b> - %s\n' % tuple(map(gobject.markup_escape_text, (alias.name, alias.target))))
开发者ID:zsx,项目名称:hotwire,代码行数:42,代码来源:help.py

示例5: execute

 def execute(self, context, args, options=[]):       
     regexp = args[0]
     if len(args) == 2:
         path = args[1]
     else:
         path = context.cwd
     regexp = args[0]
     comp_regexp = re.compile(regexp, (('-i' in options) and re.IGNORECASE or 0) | re.UNICODE)
     walk_builtin = BuiltinRegistry.getInstance()['walk']
     newctx = HotwireContext(context.cwd)
     for fobj in walk_builtin.execute(newctx, [path]):
         fp = None
         try:
             fp = open_text_file(fobj.path) 
             for i,line in enumerate(fp):
                 match = comp_regexp.search(line)
                 if match:
                     yield FileStringMatch(fobj.path, line[:-1], i, match.start(), match.end())
             fp.close()
         except OSError as e:
             pass
         except UnicodeDecodeError as e:
             pass
开发者ID:sandeep-datta,项目名称:hotwire,代码行数:23,代码来源:fsearch.py

示例6: execute

 def execute(self, context, args):
     builtins = BuiltinRegistry.getInstance()        
     yield HelpItem([builtins[x] for x in args])
开发者ID:EmilyDirsh,项目名称:hotwire-shell,代码行数:3,代码来源:help.py

示例7: super

        super(WriteBuiltin, self).__init__('write',
                                           input=InputStreamSchema('any', optional=False),
                                           argspec=MultiArgSpec('paths', min=1),
                                           options=[['-a', '--append'],['-p', '--pickle'],
                                                    ['-n', '--newline']])

    def execute(self, context, args, options=[]):
        open_mode = ('-a' in options) and 'a+' or 'w'
        do_pickle = '-p' in options
        with_newline = '-n' in options
        if do_pickle:
            open_mode = 'wb'
        if not context.input:
            return
        streams = map(lambda x: open_text_file(FilePath(x, context.cwd), open_mode), args)
        if not do_pickle:
            for arg in context.input:
                for stream in streams:
                    stream.write('%s' % (unicode(arg),))
                    if with_newline:
                        stream.write('\n')
        else:
            # Kind of annoying pickle makes you do this.
            arglist = list(context.input)
            for stream in streams:
                pickle.dump(arglist, stream)
        map(lambda x: x.close(), streams)
        return []

BuiltinRegistry.getInstance().register_hotwire(WriteBuiltin())
开发者ID:EmilyDirsh,项目名称:hotwire-shell,代码行数:30,代码来源:write.py

示例8: StringifyBuiltin

# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE X CONSORTIUM BE 
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR 
# THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import re

from hotwire.builtin import Builtin, BuiltinRegistry, InputStreamSchema

class StringifyBuiltin(Builtin):
    __doc__ = _("""Convert output to a string.""")
    def __init__(self):
        super(StringifyBuiltin, self).__init__('stringify',
                                               input=InputStreamSchema('any'),
                                               output=str,
                                               argspec=None)

    def execute(self, context, args, options=[]):
        if len(args) != 0:
            raise ValueError(_("Too many arguments specified"))
        for arg in context.input:
            if not isinstance(arg, basestring):
                yield str(arg)
            else:
                yield arg
BuiltinRegistry.getInstance().register_hotwire(StringifyBuiltin())
开发者ID:EmilyDirsh,项目名称:hotwire-shell,代码行数:30,代码来源:stringify.py

示例9: execute

    def execute(self, context, args, options=[]):     
        if len(args) == 1:
            target_prop = args[0]
        else:
            target_prop = None
        count_obj = '-c' in options
        order_unique_items = []
        unique_items = {}
        for arg in context.input:
            if target_prop is not None:
                value = getattr(arg, target_prop)
            else:
                value = arg
            if value in unique_items:
                if count_obj:
                    unique_items[value] += 1
                continue
            unique_items[value] = 1
            if count_obj:
                # keep order while counting
                order_unique_items.append(value)
            else:
                yield value
        if count_obj:
            for item in order_unique_items:
                yield (unique_items[item], item)
                        

BuiltinRegistry.getInstance().register_hotwire(UniqBuiltin())
开发者ID:EmilyDirsh,项目名称:hotwire-shell,代码行数:29,代码来源:uniq.py

示例10: ViewBuiltin

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE X CONSORTIUM BE 
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR 
# THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import os,sys,re,os.path, stat,subprocess

from hotwire.builtin import Builtin, BuiltinRegistry, MultiArgSpec
from hotwire.fs import FilePath
from hotwire.sysdep.fs import Filesystem

class ViewBuiltin(Builtin):
    __doc__ = _("""Launch the text viewer.""")
    
    def __init__(self):
        super(ViewBuiltin, self).__init__('view',
                                          nodisplay=True,
                                          argspec=MultiArgSpec('paths', min=1),
                                          idempotent=True,
                                          threaded=False)
 
    def execute(self, context, args):
        from hotwire_ui.adaptors.editors import EditorRegistry
        prefeditor = EditorRegistry.getInstance().get_preferred()
        prefeditor.run_many_readonly(context.cwd, *args)
        return []
BuiltinRegistry.getInstance().register_hotwire(ViewBuiltin())
开发者ID:EmilyDirsh,项目名称:hotwire-shell,代码行数:29,代码来源:view.py

示例11: _expand_verb_completion

 def _expand_verb_completion(self, completion):
     target = completion.target
     if isinstance(target, File):
         return (BuiltinRegistry.getInstance()['sys'], [target.path])       
开发者ID:zsx,项目名称:hotwire,代码行数:4,代码来源:command.py

示例12: super

        super(LossyObjectJSONDumper, self).__init__(*args, **kwargs)
        
    def default(self, o):
        name_repr = {}
        for name,member in sorted(inspect.getmembers(o), lambda a,b: locale.strcoll(a[0],b[0])):
            if name.startswith('_'):
                continue
            name_repr[name] = str(type(member))
        return self.encode(name_repr)

class JsonBuiltin(Builtin):
    __doc__ = _("""Convert object stream to JSON.""")
    def __init__(self):
        super(JsonBuiltin, self).__init__('json',
                                          output=str, # 'any'
                                          input=InputStreamSchema('any'),
                                          idempotent=True,
                                          argspec=None)

    def execute(self, context, args, options=[]):
        out = StringIO()
        for o in context.input:
            simplejson.dump(o, out, indent=2, cls=LossyObjectJSONDumper)
        # Should support binary streaming            
        for line in StringIO(out.getvalue()):
            if line.endswith('\n'):
                yield line[0:-1]
            else:
                yield line
BuiltinRegistry.getInstance().register_hotwire(JsonBuiltin())
开发者ID:EmilyDirsh,项目名称:hotwire-shell,代码行数:30,代码来源:json.py

示例13: HelpItem

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE X CONSORTIUM BE 
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR 
# THE USE OR OTHER DEALINGS IN THE SOFTWARE.

from hotwire.builtin import Builtin, BuiltinRegistry, ArgSpec

from hotwire.completion import BuiltinCompleter

class HelpItem(object):
    def __init__(self, items):
        self.items = items

class HelpBuiltin(Builtin):
    __doc__ = _("""Display help.""")
    def __init__(self):
        super(HelpBuiltin, self).__init__('help',
                                          output=HelpItem,
                                          argspec=(ArgSpec('builtin', opt=True),))

    def get_completer(self, context, args, i):
        return BuiltinCompleter()

    def execute(self, context, args):    
        yield HelpItem(args)
            
    
BuiltinRegistry.getInstance().register_hotwire(HelpBuiltin())
开发者ID:zsx,项目名称:hotwire,代码行数:30,代码来源:help.py

示例14: getattr

            prop = args[1]
        else:
            prop = None
        regexp = args[0]
        target_prop = prop
        invert = '-v' in options
        stringify = '-s' in options
        compiled_re = re.compile(regexp, (('-i' in options) and re.IGNORECASE or 0) | re.UNICODE)
        for arg in context.input:
            if target_prop is not None:
                target_propvalue = getattr(arg, target_prop)
            else:
                target_propvalue = arg
            if not isinstance(target_propvalue, str):
                if not stringify:
                    raise ValueError(_("Value not a string: %r" % (target_propvalue,)))
                else:
                    target_propvalue = repr(target_propvalue)
            elif not isinstance(target_propvalue, str):
                target_propvalue = str(target_propvalue, 'utf-8')                
                        
            match = compiled_re.search(target_propvalue)
            if invert:
                match = not match
            if match:
                if isinstance(arg, str):
                    yield StringMatch(target_propvalue, match)
                else:
                    yield arg
BuiltinRegistry.getInstance().register_hotwire(FilterBuiltin())
开发者ID:sandeep-datta,项目名称:hotwire,代码行数:30,代码来源:filter.py

示例15: NewlineBuiltin

# The above copyright notice and this permission notice shall be included in all 
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE X CONSORTIUM BE 
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR 
# THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import re

from hotwire.builtin import Builtin, BuiltinRegistry, InputStreamSchema

class NewlineBuiltin(Builtin):
    __doc__ = _("""Convert output to a string, and add a newline if necessary.""")
    def __init__(self):
        super(NewlineBuiltin, self).__init__('newline',
                                             input=InputStreamSchema('any'),
                                             output=str,
                                             argspec=None)

    def execute(self, context, args, options=[]):
        for arg in context.input:
            if not isinstance(arg, str):
                arg = str(arg) 
            if not arg.endswith('\n'):
                arg += '\n'
            yield arg
BuiltinRegistry.getInstance().register_hotwire(NewlineBuiltin())
开发者ID:sandeep-datta,项目名称:hotwire,代码行数:30,代码来源:newline.py


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