惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
C
CXSECURITY Database RSS Feed - CXSecurity.com
L
LINUX DO - 热门话题
S
Secure Thoughts
TaoSecurity Blog
TaoSecurity Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
T
Threat Research - Cisco Blogs
AI
AI
B
Blog RSS Feed
S
Schneier on Security
雷峰网
雷峰网
Schneier on Security
Schneier on Security
Help Net Security
Help Net Security
Cloudbric
Cloudbric
L
LINUX DO - 最新话题
罗磊的独立博客
有赞技术团队
有赞技术团队
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Apple Machine Learning Research
Apple Machine Learning Research
P
Proofpoint News Feed
酷 壳 – CoolShell
酷 壳 – CoolShell
The Hacker News
The Hacker News
博客园 - Franky
Attack and Defense Labs
Attack and Defense Labs
The Cloudflare Blog
Webroot Blog
Webroot Blog
Last Week in AI
Last Week in AI
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
博客园 - 叶小钗
美团技术团队
L
Lohrmann on Cybersecurity
T
The Blog of Author Tim Ferriss
The Last Watchdog
The Last Watchdog
T
Troy Hunt's Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Vercel News
Vercel News
Know Your Adversary
Know Your Adversary
O
OpenAI News
博客园 - 【当耐特】
Hacker News - Newest:
Hacker News - Newest: "LLM"
C
Cybersecurity and Infrastructure Security Agency CISA
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
www.infosecurity-magazine.com
www.infosecurity-magazine.com
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
PCI Perspectives
PCI Perspectives
H
Heimdal Security Blog
I
InfoQ
GbyAI
GbyAI
T
Threatpost
C
Cisco Blogs

夜行人

回家路上 第一期的直播演示项目 震动检测器 正能量 在线参观CodeLab Neverland 发布 CodeLab Adapter 3.3.1 DynamicTable 之 纸糊方向盘 CodeLab DynamicTable: 一个可实施的技术方案 CodeLab Insight 发布 Alpha 版 情人节 Home Assistant 周报 && IoT 周报 (02) Joplin: 关注隐私的 Evernote 开源替代软件 浏览器的未来与 Web 传感器 Home Assistant 周报 && IoT 周报 (01) 百宝箱(01) 论自由 介绍 WebThings Home Assistant 周报 && iot 周报 (00) 百宝箱(00) 毛姆读书心得 传世之作 周末徒步 CodeLab Adapter ❤️ Jupyter/Python 航班 躲雨 夏令营途中 [译]思想--作为一种技术 The future of coding 美国之行 三门问题的程序模拟 从Python转向Pharo https://blog.just4fun.site/post/iot/iot-open-source-projects/ Python异步编程笔记 https://blog.just4fun.site/post/iot/iot-open-source-hardware-community/ 万物积木化开发者社区 CodeLab ❤️ Blender Scratch3技术分析之云变量 API(第7篇) [译]对管道(Pipes)的偏爱 [译]提出正确的问题比得到正确答案更重要 蓝牙设备与Scratch3.0 创建你的第一个Scratch3.0 Extension Scratch3技术分析之项目内部数据(第6篇) Scratch3技术分析之社区 API(第5篇) Scratch3技术分析之User API(第4篇) Scratch3技术分析之项目主页API(第3篇) Scratch3技术分析之静态资源API(第2篇) Scratch3.0、micro:bit与Windows7 https://blog.just4fun.site/post/iot/zerynth-vs-micropython/ 核聚变、方所与半宅空间 可视化编程为何是个糟糕的主意 codelab.club周末聚会 关于codelab.club '下一件大事'是一个房间 Hungry Robot - Eat everything 编程作为一种思考方式 今日简史 史蒂夫·乔布斯传 罗素自选文集 https://blog.just4fun.site/post/edx/tianjin-scratch-ai/ https://blog.just4fun.site/post/edx/richie-cms-openedx/ 徒步武功山 WebUSB与micro:bit 积木化编程与3D场景 夜宿武功山顶 scratch3-adapter接入优必选Alpha系列机器人 https://blog.just4fun.site/post/edx/video-migration-note/ scratch3-adapter重构笔记 https://blog.just4fun.site/post/edx/edx-community-members/ 两种硬件编程风格的比较 使用micro:bit自制PPT翻页笔 柏拉图对话集 scratch3.0 + micro:bit 七月电影放映计划 非营利组织的管理 Screenly--用树莓派让任何屏幕变为可编程的数字标牌 以最佳实践开始你的Django项目 micro:bit与事件驱动 为Scratch3.0设计的插件系统(上篇) OCR应用一例 近两年读过的一些好书 blockly开发之使用python驱动浏览器中的turtle(2) 牛顿新传 文学理论入门 逻辑的引擎 人生的意义 blockly开发之生成并运行js代码(1) blockly开发之hello world(0) micro:bit使用笔记 神器之Termux https://blog.just4fun.site/post/iot/micropython-notes/ Cozmo what is this Scratch的前世今生 下段旅程 我行在远方 爆裂 途中杂记 https://blog.just4fun.site/post/edx/open-edx-startup/ cozmo系列之入门 - 有性格且可编程的机器人 PaperWeekly开发笔记 创业二三事
[译]使用Python Prompt Toolkit构建强大的REPL
2016-07-31 · via 夜行人

文章目录

原文参考Build a REPL With Python Prompt Toolkit,很喜欢这篇教程,清晰简单,读起来十分舒服,翻译过来分析给大家

前言

正式开始翻译之前,我们先了解一些背景知识

python-prompt-toolkit

python-prompt-toolkit是一个用于构建强大交互式命令行的 Python 工具库,许多好用而智能的命令行工具都构建在它上边

  • ipython
  • ptpython
  • mycli
  • pgcli
  • xonsh
  • gitsome
  • http-prompt
  • aws-shell
  • haxor-news

如果你用过其中的一些,你会惊叹于他们的智能和良好的交互式体验(就像fish), 这些工具的背后便是我们今天的主角:python-prompt-toolkit

REPL

全称Read-Eval-Print Loop(“读取-求值-输出"循环),是一个简单的,交互式的编程环境.

REPL使得探索性的编程和调试更加便捷,因为“读取-求值-输出”循环通常会比经典的“编辑-编译-运行-调试”模式要更快

译文

本文教你使用prompt_toolkit来构建SQLite数据库的命令行工具

prompt_toolkit是一个用于构建强大交互式命令行的 Python 工具库

首先让我们用pip安装它:

pip install prompt_toolkit

搞起!

读取用户输入

使用prompt方法接收用户输入

1
2
3
4
5
6
7
8
9
from __future__ import unicode_literals
from prompt_toolkit import prompt

def main():
    text = prompt("> ")
    print('You entered:', text)

if __name__ == '__main__':
    main()

REPL循环

现在让我们在一个while循环里调用prompt方法,同时将输入历史保存在InMemoryHistory对象里

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from __future__ import unicode_literals
from prompt_toolkit import prompt
from prompt_toolkit.history import InMemoryHistory

def main():
    history = InMemoryHistory()

    while True:
        text = prompt("> ", history=history)
        print('You entered:', text)
    print('GoodBye!')

if __name__ == '__main__':
    main()

语法高亮

我们已经做了一些基础工作,现在让我们将语法高亮加入到用户的输入中。我们知道用户将会输入sql语句,我们可以使用Pygments来高亮用户的输入.lexer参数允许你设置词法分析器(译者注:lexical analyzer,简称lexer),我们将使用Pygments 库的SqlLexer来对输入做高亮处理:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from __future__ import unicode_literals
from prompt_toolkit import prompt
from prompt_toolkit.history import InMemoryHistory
from pygments.lexers import SqlLexer

def main():
    history = InMemoryHistory()

    while True:
        text = prompt('> ', lexer=SqlLexer, history=history)
        print('You entered:', text)
    print('GoodBye!')

if __name__ == '__main__':
    main()

自动补全

语法高亮屌爆啦!你造什么更牛一些吗?自动补全!开干!

使用WordCompleter类创建一个叫做sql_completer的实例,初始化的时候,定义一组关键字集合,它们将用于自动补全

sql_completer实例将被传递到prompt函数里

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from __future__ import unicode_literals
from prompt_toolkit import prompt
from prompt_toolkit.history import InMemoryHistory
from prompt_toolkit.contrib.completers import WordCompleter
from pygments.lexers import SqlLexer

sql_completer = WordCompleter(['create', 'select', 'insert', 'drop',
                               'delete', 'from', 'where', 'table'], ignore_case=True)


def main():
    history = InMemoryHistory()

    while True:
        text = prompt('> ', lexer=SqlLexer, completer=sql_completer, history=history)
        print('You entered:', text)
    print('GoodBye!')

if __name__ == '__main__':
    main()

大约用了30行代码我们就得到了一个拥有自动补全和语法高亮的REPL。 再接再厉!

修改菜单样式

自动补全菜单忒丑,让我们给它点"颜色"看看!创建DocumentStyle,使它成为pygments.style的子类. 定制自动补全菜单的颜色,并把样式作为参数传到prompt函数里:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from __future__ import unicode_literals
from prompt_toolkit import prompt
from prompt_toolkit.history import InMemoryHistory
from prompt_toolkit.contrib.completers import WordCompleter
from pygments.lexers import SqlLexer
from pygments.style import Style
from pygments.token import Token
from pygments.styles.default import DefaultStyle

sql_completer = WordCompleter(['create', 'select', 'insert', 'drop',
                               'delete', 'from', 'where', 'table'], ignore_case=True)

class DocumentStyle(Style):
    styles = {
        Token.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000',
        Token.Menu.Completions.Completion: 'bg:#008888 #ffffff',
        Token.Menu.Completions.ProgressButton: 'bg:#003333',
        Token.Menu.Completions.ProgressBar: 'bg:#00aaaa',
    }
    styles.update(DefaultStyle.styles)

def main():
    history = InMemoryHistory()

    while True:
        text = prompt('> ', lexer=SqlLexer, completer=sql_completer,
                      style=DocumentStyle, history=history)
        print('You entered:', text)
    print('GoodBye!')

if __name__ == '__main__':
    main()

剩下的工作就是如何对接到sqlite后端,作为读者的家庭作业好了。哈哈开玩笑啦…我们继续

对接到Sqlite

这一步是可选的 ;) 之前我们一直在关注如何构建REPL. 现在是时候将输入传给SQLite

显然我没有考虑错误处理,但它或许可以作为你们的起步参考

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from __future__ import unicode_literals
import sys
import sqlite3

from prompt_toolkit import prompt, AbortAction
from prompt_toolkit.history import InMemoryHistory
from prompt_toolkit.contrib.completers import WordCompleter
from pygments.lexers import SqlLexer
from pygments.style import Style
from pygments.token import Token
from pygments.styles.default import DefaultStyle

sql_completer = WordCompleter(['create', 'select', 'insert', 'drop',
                               'delete', 'from', 'where', 'table'], ignore_case=True)

class DocumentStyle(Style):
    styles = {
        Token.Menu.Completions.Completion.Current: 'bg:#00aaaa #000000',
        Token.Menu.Completions.Completion: 'bg:#008888 #ffffff',
        Token.Menu.Completions.ProgressButton: 'bg:#003333',
        Token.Menu.Completions.ProgressBar: 'bg:#00aaaa',
    }
    styles.update(DefaultStyle.styles)

def main(database):
    history = InMemoryHistory()
    connection = sqlite3.connect(database)

    while True:
        try:
            text = prompt('> ', lexer=SqlLexer, completer=sql_completer,
                          style=DocumentStyle, history=history,
                          on_abort=AbortAction.RETRY)
        except EOFError:
            break  # Control-D pressed.
        with connection:
            messages = connection.execute(text)
            for message in messages:
                print(message)
    print('GoodBye!')

if __name__ == '__main__':
    if len(sys.argv) < 2:
        db = ':memory:'
    else:
        db = sys.argv[1]

    main(db)

希望这篇文章能给你一些启发去构建命令行工具

以上

附录

unicode

在python2中使用from __future__ import unicode_literals,这样一来所有字符串将被解释为unicode,无论是否有u'',这样一来和python3保持了一致

example

python-prompt-toolkit的教程写得极好,通过examples,花很短的时间,我们就能学会如何使用python-prompt-toolkit的丰富特性

文章作者 种瓜

上次更新 2016-07-31