一个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 Spring框架服务单元测试   在Java中遍历hashmaps的hashmap以检索字符串值   如何使用CodeQL检查Java注释是否具有特定属性?   java为什么在Spring Boot中访问此资源而不是登录弹出窗口需要始终获得完全身份验证   处理将多集计数转换为列表的过程   java另一个线性布局,没有出现按钮   eclipse Java映像加载未显示在jar中   java Junit类无法加载基本测试类ApplicationContext   java如何在main中使用my getvalues()方法打印列表   java Sonar,S128:切换案例应该以无条件的“中断”语句结束,而不是继续   java从socket读取字符串错误连接重置错误   java使用新数据刷新任意图表饼图   java通过异步运行lambda访问方法参数   java错误的结果一旦我处理try and catch