python动态时钟源码_使用python的curses库实现的动态时钟

#!/usr/bin/python

# coding=utf-8

version = "0.0.1"

import signal

signal.signal(signal.SIGINT, signal.SIG_IGN) # ctrl+c

import curses

import time

import datetime

import os

import sys

import subprocess

import optparse

class CursesHandle:

def __init__ (self):

'''设置字符串输出位置x与y'''

self.x = 0

self.y = 0

self.stdscr = None

def __enter__ (self):

'''with使用,初始化curses并设置环境,start_color()、init_pair设置文字与背景颜色'''

self.stdscr = curses.initscr()

curses.start_color()

curses.use_default_colors()

curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)

curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK)

curses.noecho()

curses.cbreak()

curses.curs_set(False)

self.stdscr.keypad(1)

self.stdscr.nodelay(1)

return self

def __exit__ (self, exc_ty, exc_val, tb):

'''with使用,退出时还原环境'''

curses.nocbreak()

self.stdscr.keypad(0)

curses.echo()

curses.endwin()

curses.curs_set(True)

self.stdscr = None

def display_info (self, words, color=1, x=None, y=None):

if x is None:

x = self.x

if y is None:

y = self.y

'''打印words字符串,color为1绿2红,在环境里已设置'''

if self.stdscr is None:

raise Exception('ERROR: Not self.stdscr exist!')

self.stdscr.addstr(y, x, words, curses.color_pair(color))

self.stdscr.refresh()

def get_input_and_continue (self):

'''设置中断,等待输入后恢复'''

if self.stdscr is None:

raise Exception('ERROR: Not self.stdscr exist!')

self.stdscr.nodelay(0)

ch = self.stdscr.getch()

self.stdscr.nodelay(1)

def get_input_and_exit (self):

'''当输入字符为q后退出'''

if self.stdscr is None:

raise Exception('ERROR: Not self.stdscr exist!')

ch = self.stdscr.getch()

if ch == ord('q'):

exit(0)

STYLE = {

'fore':

{ # 前景色

'black' : 30, # 黑色

'red' : 31, # 红色

'green' : 32, # 绿色

'yellow' : 33, # 黄色

'blue' : 34, # 蓝色

'purple' : 35, # 紫红色

'cyan' : 36, # 青蓝色

'white' : 37, # 白色

},

'back' :

{ # 背景

'black' : 40, # 黑色

'red' : 41, # 红色

'green' : 42, # 绿色

'yellow' : 43, # 黄色

'blue' : 44, # 蓝色

'purple' : 45, # 紫红色

'cyan' : 46, # 青蓝色

'white' : 47, # 白色

},

'mode' :

{ # 显示模式

'mormal' : 0, # 终端默认设置

'bold' : 1, # 高亮显示

'underline' : 4, # 使用下划线

'blink' : 5, # 闪烁

'invert' : 7, # 反白显示

'hide' : 8, # 不可见

},

'default' :

{

'end' : 0,

},

}

def UseStyle (string, mode = '', fore = '', back = ''):

mode = '%s' % STYLE['mode'][mode] if mode in STYLE['mode'] else ''

fore = '%s' % STYLE['fore'][fore] if fore in STYLE['fore'] else ''

back = '%s' % STYLE['back'][back] if back in STYLE['back'] else ''

style = ';'.join([s for s in [mode, fore, back] if s])

style = '\033[%sm' % style if style else ''

end = '\033[%sm' % STYLE['default']['end'] if style else ''

return '%s%s%s' % (style, string, end)

if __name__ == '__main__':

Usage = "usage: \n -h, --help show this help message and exit.\n %s if your terminal's height is lower than 20 columns, %s may not running."\

%(UseStyle("Warning:", fore = "black", back = "red"), UseStyle(sys.argv[0], mode = 'underline'))

parser = optparse.OptionParser(usage=Usage)

parser.add_option('-v','--version',dest='is_show_version', action="store_true", help='get version')

options,args=parser.parse_args()

if options.is_show_version == True:

print("version: %s"%version)

exit(0)

if not (os.path.exists("/usr/bin/figlet") or

os.path.exists("/bin/figlet") or

os.path.exists("/sbin/figlet") or

os.path.exists("/usr/sbin/figlet")):

print("\ndependence '%s' not found in:\n"%UseStyle('figlet', mode = 'underline'))

print(" /usr/bin")

print(" /usr/sbin")

print(" /bin")

print(" /sbin")

print("\nTry: apt install figlet\n")

exit(-1)

with CursesHandle() as cur:

try:

cur.display_info('press \'q\' to exit.', 1, 0, 20)

except:

print("your terminal height is too small to support %s"\

%UseStyle('curses', mode = 'underline'))

exit(-1)

while True:

now_time = datetime.datetime.now().strftime('%m%d %H:%M:%S')

now_time_list = list(now_time)

for index, element in enumerate(now_time_list):

if element == "1" and \

index != len(now_time_list)-1 and \

now_time_list[index + 1] == "1":

now_time_list.insert(index + 1," ")

now_time = "".join(now_time_list)

now_time_pic = subprocess.check_output(["figlet", now_time])

try:

cur.display_info(now_time_pic, x=0, y=5)

except:

print("your terminal height is too small to support %s" \

%UseStyle('curses', mode = 'underline'))

exit(-1)

cur.get_input_and_exit()

time.sleep(0.1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值