• 部分转载自:python curses使用
  • pythonlab
  • pythonlab 彩色终端
  • 官方API
  • 可爱的 Python:Curses 编程

简介

  • python 中curses封装了c语言的curses,把c中复制部分简单化,比如addstr(),mvaddstr(),mvwaddstr()合并成了一个addstr()方法

语法入门

打开和关闭一个curses 应用程序

  • 在任何代码执行前都先要初始化curses。初始化操作就是调用initscr()函数,如下。该函数根据不同设备返回一个window对象代表整个屏幕,这个window对象通常叫做stdscr,和c语言报错一致。
import curses
stdscr = curses.initscr()
  • 使用curses通常要关闭屏幕回显,目的是读取字符仅在适当的环境下输出。这就需要调用noecho()方法
curses.noecho()
  • 应用程序一般是立即响应的,即不需要按回车就立即回应的,这种模式叫cbreak模式,相反的常用的模式是缓冲输入模式。开启立即cbreak模式代码如下。
curses.cbreak()
  • 终端经常返回特殊键作为一个多字节的转义序列,比如光标键,或者导航键比如Page UP和Home键 。curses可以针对这些序列做一次处理,比如curses.KEY_LEFT返回一个特殊的值。要完成这些工作,必须开启键盘模式。
stdscr.keypad(1)
  • 关闭curses非常简单,如下:
curses.nocbreak()#关闭字符终端功能(只有回车时才发生终端)
stdscr.keypad(0)
curses.echo() #打开输入回显功能
  • 调用endwin()恢复默认设置
curses.endwin()
  • 调试curses时常见的问题就是curses应用程序结束后没有重置终端到之前的状态,把终端弄的一团糟。python中该问题经常是因为代码有bug,发送异常引起的。比如键盘敲入字符后屏幕不回显,这让shell用起来非常困难。
  • 为了避免这样的问题,可以导入curses.wrapper模块。这个函数做了一些初始化的工作,包括上面提到的和颜色的初始化。然后再执行你提供的函数,最后重置。而且被调用的函数写在try-catch中。

打开新窗口和pad

  • 通常调用initscr()获取一个window对象代表全部屏幕。但是很多程序希望划分屏幕为几个小的窗口,为了重绘,擦出这些工作在小窗口中独立进行。newwin()函数就是用来新建一个新的窗口,需要给定窗口尺寸,并返回新的window对象的。
begin_x = 20;
begin_y = 7;
height = 5;
width = 40;
win = curses.newwin(height, width, begin_y, begin_x)
  • 注意:坐标通过是先y后x。这和别的坐标系统不同,但是根深蒂固,写的时候就这样现在改太晚喽。
  • 当调用一个方法去显示或者擦除文本时,效果不会立即显示。 为了减少屏幕重绘的时间,curses就先累积这些操作,用一种更有效的方式去显示。就比如说你的程序先在窗口显示了几个字符,然后就清除屏幕,那就没必要发送初始字符了,因为它们不会被显示。
  • 因此,curses需要你使用refresh()函数明确指出重绘窗口。
  • pad是window的特例。pad可以比显示的屏幕大,一次只显示pad的一部分。创建一个pad很简单,只需要提供宽高即可。但是刷新pad需要提供屏幕上显示的部分pad的坐标。
pad = curses.newpad(100, 100)
#  These loops fill the pad with letters; this is# explained in the next sectionfor y in range(0, 100):
for x in range(0, 100):try:pad.addch(y,x, ord('a') + (x*x+y*y) % 26)except curses.error:pass#  Displays a section of the pad in the middle of the screenpad.refresh(0,0, 5,5, 20,75)
  • 同时由多个window或者多个pad,有一问题:刷新某个window或pad时屏幕会闪烁。
  • 避免闪烁的方法:在每个window调用noutrefresh()方法。 然后使用refresh()方法的最后再调用doupdate()方法。

显示文本

  • addscr不同格式如下:如果没有坐标,字符显示在上一次操作完的位置。
Form                        Description
str or ch                   Display the string str or character ch at the current position
str or ch, attr             Display the string str or character ch, using attribute attr at the current position
y, x, str or ch             Move to position y,x within the window, and display str or ch
y, x, str or ch, attr       Move to position y,x within the window, and display str or ch, using attribute attr
  • 属性可以让文本高亮显示,比如黑体,下划线,倒序,彩色显示。

属性和颜色

  • 属性和描述:
Attribute       Description
A_BLINK         Blinking text
A_BOLD          Extra bright or bold text
A_DIM           Half bright text
A_REVERSE       Reverse-video text
A_STANDOUT      The best highlighting mode available
A_UNDERLINE     Underlined text
  • 屏幕第一行reverse-video显示。
stdscr.addstr(0, 0, "Current mode: Typing mode", curses.A_REVERSE)
stdscr.refresh()
  • curses使用前景色和背景色,可通过color_pair()方法获取一对颜色。
  • 使用颜色对1显示一行
stdscr.addstr("Pretty text", curses.color_pair(1))
stdscr.refresh()
  • start_color()初始化了8中基本颜色:0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and 7:white。
  • init_pair(n,f,b)修改颜色对n,让f为前景色,b为背景色。颜色对0天生的黑白色,不允许改。
  • 比如:修改color1为红色文本,白色背景:
  • curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)
  • 使用:
  • stdscr.addstr(0,0, “RED ALERT!”, curses.color_pair(1))

用户输入

  • 获取输入一遍使用getch()方法,这个方法暂停等待用户输入,显示用echo()方法。
  • getch()返回一个整数 ,在0到255之间,表示输入字符的ASCII值。打印255的是些特殊字符,比如Page Up,Home。
  • 代码经常这样写
while 1:c = stdscr.getch()if c == ord('p'):PrintDocument()elif c == ord('q'):break# Exit the while()elif c == curses.KEY_HOME:x = y = 0
  • getstr()获取一个字符串。因为功能有限不常用。
  • curses.echo() # Enable echoing of characters# Get a 15-character string, with the cursor on the top lines = stdscr.getstr(0,0, 15)

例子

  • 代码如下:
#-*- coding: UTF-8 -*-
import curses
stdscr = curses.initscr()
def display_info(str, x, y, colorpair=2):'''''使用指定的colorpair显示文字'''global stdscrstdscr.addstr(y, x,str, curses.color_pair(colorpair))stdscr.refresh()
def get_ch_and_continue():'''''演示press any key to continue'''global stdscr#设置nodelay,为0时会变成阻塞式等待    stdscr.nodelay(0)#输入一个字符    ch=stdscr.getch()#重置nodelay,使得控制台可以以非阻塞的方式接受控制台输入,超时1秒    stdscr.nodelay(1)return True
def set_win():'''''控制台设置'''global stdscr#使用颜色首先需要调用这个方法    curses.start_color()#文字和背景色设置,设置了两个color pair,分别为1和2    curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK)#关闭屏幕回显    curses.noecho()#输入时不需要回车确认    curses.cbreak()#设置nodelay,使得控制台可以以非阻塞的方式接受控制台输入,超时1秒    stdscr.nodelay(1)
def unset_win():'''控制台重置'''global stdstr#恢复控制台默认设置(若不恢复,会导致即使程序结束退出了,控制台仍然是没有回显的)    curses.nocbreak()stdscr.keypad(0)curses.echo()#结束窗口    curses.endwin()
if__name__=='__main__':try:set_win()display_info('Hola, curses!',0,5)display_info('Press any key to continue...',0,10)get_ch_and_continue()except Exception,e:raise efinally:unset_win()
  • 执行:# python testcurses.py

排错

[root@yl-web-test srv]# python curses.pyTraceback (most recent call last):File "curses.py", line 2, in <module>import cursesFile "/srv/curses.py", line 4, in <module>    stdscr = curses.initscr()
AttributeError: 'module' object has no attribute 'initscr'
  • 原因:因为我的文件取名是curses.py,而系统也是用的curses.py,python执行时先从当前目录查找,所以不能和系统文件重名。
  • 换个名字,比如改名为testcurses.py 就好了。

小例子

  • 在Python中使用NCurses,下面是一个小例程
import curses
myscreen = curses.initscr()
myscreen.border(0)
myscreen.addstr(12, 25, "Python curses in action!")
myscreen.refresh()
myscreen.getch()
curses.endwin()
  • 注意这个示例中的第一行import curses,表明使用curses库,然后这个示像在屏幕中间输出“Python curses in action!”字样,
  • 其中坐标为12, 25,注意,在字符界面下,80 x 25是屏幕大小,其用的是字符,而不是像素
  • 我们再来看一个数字菜单的示例
#!/usr/bin/env python
from os import system
import curses
def get_param(prompt_string):screen.clear()screen.border(0)screen.addstr(2, 2, prompt_string)screen.refresh()input = screen.getstr(10, 10, 60)return input
def execute_cmd(cmd_string):system("clear")a = system(cmd_string)print ""if a == 0:print "Command executed correctly"else:print "Command terminated with error"raw_input("Press enter")print ""
x = 0
while x != ord('4'):screen = curses.initscr()screen.clear()screen.border(0)screen.addstr(2, 2, "Please enter a number...")screen.addstr(4, 4, "1 - Add a user")screen.addstr(5, 4, "2 - Restart Apache")screen.addstr(6, 4, "3 - Show disk space")screen.addstr(7, 4, "4 - Exit")screen.refresh()x = screen.getch()if x == ord('1'):username = get_param("Enter the username")homedir = get_param("Enter the home directory, eg /home/nate")groups = get_param("Enter comma-separated groups, eg adm,dialout,cdrom")shell = get_param("Enter the shell, eg /bin/bash:")curses.endwin()execute_cmd("useradd -d " + homedir + " -g 1000 -G " + groups + " -m -s " + shell + " " + username)if x == ord('2'):curses.endwin()execute_cmd("apachectl restart")if x == ord('3'):curses.endwin()execute_cmd("df -h")
curses.endwin()

Python Curses相关推荐

  1. python编辑器和终端_从python curses程序运行终端文本编辑器

    我想在python curses程序中使用外部终端文本编辑器和寻呼机.我使用子进程库.在大多数情况下,它工作得很好,除了当我退出文本编辑器时(与nemo和vi相同),我不能再次使光标不可见.另外,在调 ...

  2. Python curses使用

    windows下使用 安装whl库 Python本身不支持curses,需要安装whl 先在pip目录下安装wheel: pip install wheel 下载whl文件(选择符合自己版本的) 下载 ...

  3. 【Python随记】:curses 库的快速入门

    文章目录 curses 简介 Python curses 模块 curses 库安装方法 Windows 下安装 Linux 下安装 curses 简介 curses 是一个在Linux/Unix下广 ...

  4. python curses_python curses 使用

    原标题:python curses 使用 (点击上方蓝字,快速关注我们) 来源:starof www.cnblogs.com/starof/p/4703820.html python 中curses封 ...

  5. python curses_简单的Python的curses库使用教程

    curses 库 ( ncurses ) 提供了控制字符屏幕的独立于终端的方法.curses 是大多数类似于 UNIX 的系统(包括 Linux)的标准部分,而且它已经移植到 Windows 和其它系 ...

  6. python调用ch_python curses使用

    python 中curses封装了c语言的curses,把c中复杂部分简单化,比如addstr(),mvaddstr(),mvwaddstr()合并成了一个addstr()方法. 一.语法入门 1.打 ...

  7. python keyboard backspace_Python curses.KEY_BACKSPACE屬性代碼示例

    本文整理匯總了Python中curses.KEY_BACKSPACE屬性的典型用法代碼示例.如果您正苦於以下問題:Python curses.KEY_BACKSPACE屬性的具體用法?Python c ...

  8. python获取文本光标_使用python readline时如何获取(并设置)当前bash光标位置?

    我可以建议 Python curses吗? The curses module provides an interface to the curses library, the de-facto st ...

  9. Python 文本终端 GUI 框架,太酷了

    来源:Python技术 上次发了一篇基于 Webview 的图形界面的程序 制作后,有读者询问:有没有基于文本中终端的 GUI 开发框架? 今天笔者就带大家,梳理几个常见的基于文本终端的 UI 框架, ...

最新文章

  1. Javascript全局变量和delete
  2. 实体框架高级应用之动态过滤 EntityFramework DynamicFilters
  3. codewars-013: Ease the StockBroker
  4. 《演讲之禅》助你成长为一名合格程序员
  5. C# 把字符串类型日期转换为日期类型
  6. Gigabit Ethernet复制数据会异常的缓慢
  7. 【Transformer】CSWin Transformer: A General Vision Transformer Backbone with Cross-Shaped Windows
  8. python语言的两种注释方法_python编程时添加中文注释的方法
  9. 一个网站自动化测试程序的设计与实现
  10. 工业以太网在工业领域的应用特点详解
  11. java 秒杀多线程_秒杀多线程系列 - 随笔分类 - Joyfulmath - 博客园
  12. vb外部调用autocad_AutoCAD教程之图块的各种相关操作和概念
  13. 大东电报与雷格斯在全球部署宝利通高清系统
  14. 区块链开发公司 注重用户的价值才是企业归宿
  15. win2003域迁移实战记录
  16. C语言程序设计-谭浩强第五版习题【答案解析】2022.5.10
  17. 矩阵分析之 实矩阵分解(4)满秩分解,QR分解
  18. 简单维修MacBook Air——更换SSD硬盘
  19. 计算机打印机无法共享怎么设置密码,打印机共享设置密码【调解思路】
  20. 八叉树的范围和射线检测

热门文章

  1. 信息论与编码-python实现三种编码(香农编码,费诺编码,赫夫曼编码)
  2. MFC 下拉列表框的设置
  3. n皇后问题回溯法-迭代实现
  4. #include < > 和 #include “ “ 的区别
  5. 人机猜拳代码python_python 实现人和电脑猜拳的示例代码
  6. 基于区块链溯源系统后端开发
  7. 必须得会的汽车ECU研发基础--ECU软件架构概览3
  8. 嵌入式Linux的内核编译
  9. OpenCV的基本矩阵操作与示例
  10. 计算机一级表格减法,怎么把表格的数字全部加减