一个redis支持的repl,它保存命令历史记录、输出和错误

chloop的Python项目详细描述


安装

安装redis并启动服务器

% sudo apt-get install -y redis-server

or

% brew install redis@3.2
% brew services start redis@3.2

使用pip

安装
% pip3 install chloop

用法

GetCharLoop类由chloop包提供。打电话 此类的实例启动repl会话,用户可以 按Ctrl+dCtrl+c结束。

See the Example section below.

在repl提示符下键入的第一个字符很重要。

结肠

在提示符处按:键将允许您输入命令 以及任何需要传递给该命令的参数。

  • :docstrings查看类中定义的方法的docstrings
  • :errors查看引发异常的冒号命令
  • :historyview冒号命令已发出
  • :pdb启动pdb会话(调试/检查)
  • :ipython启动ipython shell
  • :shortcuts查看快捷键

添加到GetCharLoop子类中的任何方法都可以调用为 冒号命令,只要它们不以下划线开头 (_)。方法应该只接受`*args`,如果有的话。

对于不应记录到历史记录中的任何方法/命令, 将方法名追加到self._DONT_LOG_CMDS列表的末尾。

破折号

在提示符处按-键将允许您键入注释。

问号

在提示符处按?键将显示docstring类 以及启动消息。

其他键

在提示下按任何其他键将执行下列操作之一:

  • 调用绑定到键的注册快捷函数(使用 :shortcuts查看可用内容的命令)
  • 显示字符及其整数序数

热键可以绑定到任何不接受参数的可调用对象。

Use ^{tt21}$ (if necessary) to create a callable accepting no arguments.

添加热键(简单)

  • 对^{tt2}的实例调用_add_hotkey方法$ (或子类)具有以下参数
    • ch:字符热键
    • func:不接受参数的可调用对象
    • help_string:包含热键的简短帮助文本的字符串

添加热键(在self上使用可调用项时)

  • 在^{tt29}中调用self._chfunc_dict_update方法$ 子类的方法,具有元组列表或dict。

    • dict的键(或元组列表中的第一个项)是 热键字符

    • dict(或元组列表中的第二项)的值是 两项元组

      • 第一项是不接受参数的callable

      • 第二项是一个简短的帮助字符串

        Note: when passing a dict, the items will be inserted in the alphabetical order of the help string.

基本示例

% python3 -c 'from chloop import GetCharLoop; GetCharLoop()()'

> :docstrings
======================================================================
Loop forever, receiving character input from user and performing actions

    - ^d or ^c to break the loop
    - ':' to enter a command (and any arguments)
        - the name of the command should be monkeypatched on the GetCharLoop
          instance, or be a defined method on a GetCharLoop sub-class
        - the function bound to `:command` should accept `*args` only
    - '-' to receive an input line from user (a note)
    - '?' to show the class docstring(s) and the startup message

.:: docstrings ::.
Print/return the docstrings of methods defined on this class

.:: errors ::.
Print/return any colon commands that raised exceptions (w/ traceback)

.:: history ::.
Print/return colon commands used

.:: ipython ::.
Start ipython shell. To continue back to the input loop, use 'ctrl + d'

.:: pdb ::.
Start pdb (debugger). To continue back to the input loop, use 'c'

.:: shortcuts ::.
Print/return any hotkey shortcuts defined on this class



> :pdb
[10] > /tmp/ch/venv/lib/python3.5/site-packages/chloop/__init__.py(90)__call__()
-> continue
(Pdb++) l
 85                     cmd = user_input.split()[0]
 86                     args = user_input.split()[1:]
 87
 88                     if cmd == 'pdb':
 89                         import pdb; pdb.set_trace()
 90  ->                     continue
 91
 92                     if cmd == 'ipython':
 93                         from IPython import embed; embed()
 94                         continue
 95
(Pdb++) self._collection
Collection('chloop-log', 'default', index_fields='cmd,status,error_type', json_fields='args,value')
(Pdb++) self._collection.keyspace
[]
(Pdb++) c

> :ipython
Python 3.5.1+ (default, Mar 30 2016, 22:46:26)
Type "copyright", "credits" or "license" for more information.

IPython 5.2.2 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.


In [1]: self._collection
Out[1]: Collection('chloop-log', 'default', index_fields='cmd,status,error_type', json_fields='args,value')

In [2]: self.shortcuts
Out[2]: <bound method GetCharLoop.shortcuts of <chloop.GetCharLoop object at 0x7f9f8ff5f5f8>>

In [3]: self.docstrings
Out[3]: <bound method GetCharLoop.docstrings of <chloop.GetCharLoop object at 0x7f9f8ff5f5f8>>

In [4]:
Do you really want to exit ([y]/n)? y


> :shortcuts


> - there are no shortcuts defined by default

>

子类示例

  • 导入GetCharLoop并将其子类

  • 初始化子类并调用它

    Save the following to ^{tt31}$

from functools import partial
from chloop import GetCharLoop


class Mine(GetCharLoop):
    """A sub-class of GetCharLoop"""
    def __init__(self, *args, **kwargs):
        # Process any extra/custom kwargs here and set some attributes
        self._mything = kwargs.pop('mything', 'some default value')

        super(Mine, self).__init__(*args, **kwargs)

        # Add some single-key shorcuts that call methods on `self`
        self._chfunc_dict_update([
            ('h', (self.history,
                  'display recent command history')),
            ('e', (self.errors,
                  'display recent errors')),
        ])


    def somefunc(self, *args):
        """Joins the args passed to it into a string"""
        args_as_one = ' '.join(args)
        print(repr(args_as_one))
        return args_as_one

    def lame(self):
        """raise exception"""
        return 1/0


if __name__ == '__main__':
    m = Mine(prompt='\nmyprompt> ')
    m._add_hotkey('a', lambda: print('hello'), 'say hello')
    m()

与repl进行交互

Assuming the above code is in a file called ^{tt31}$
% python mine.py

myprompt> :somefunc here are some args
u'here are some args'

myprompt> :shortcuts
'e' -- display recent errors
'h' -- display recent command history
'a' -- say hello

myprompt> a
hello

myprompt> :lame
======================================================================
Traceback (most recent call last):
  File "/home/ken/chloop/chloop/__init__.py", line 232, in __call__
    value = cmd_func()
  File "main.py", line 33, in lame
    return 1/0
ZeroDivisionError: integer division or modulo by zero

cmd: u'lame'
args: []

myprompt> :pdb
...

myprompt> e
(errors output)

myprompt> - here is a note

myprompt> - here is another note

myprompt>

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java有没有工具可以将zephyr转换为velocity模板?   java在安卓 studio中从JSON响应中获取值   jvm如何在Java中设计一个好的permgen空间字符串?   java如何防止Rest webservice使用被盗令牌进行身份验证   java无法遍历列表JSTL   找不到用于ResourceServerTokenServices的java Bean SpringSecurityOauth2   java子字符串替换问题   爪哇玻璃鱼3。十、 以编程方式处理任意HTTPSession的终止   java如何检查输入是否为整数,并在最后添加一个命令来重新启动while循环?   引发java ical4j 1.0.6不可解析日期异常   Java等价于Delphi的DBCtrlGrid?   如果发生错误,java将查找下一个预期标记ANTLR 3   java自打开应用程序(创建锁屏)   java为什么netty有自己的ConcurrentHashMap?   Gradle任务中的java拉取和运行依赖项   继承与Java继承的混淆   java使用shell脚本中的版本执行jar   java我无法让Sqlite数据库与带有Maven的JavaFX应用程序IDE Eclipse包正确通信   java控制台日志未通过org打印。阿帕奇。hadoop。mapreduce。作业的waitForCompletion(true)方法   JAVAlang.NoSuchMethodError:apachestorm螺栓中的spring getrequest