從這篇開始會做一個用Python不務正業(yè)
專題匀们, 記錄Python一些一無是用但是很好玩的腳本.本期是一個終端亂彈
的腳本.
效果圖:
記得剛學shell的時候做過終端隨機的點生成隨機顏色的字符弄贿, 只為好玩和增強腳本開發(fā)技能仔涩, 下午閑來無事用python實現(xiàn)了马靠, 正好學習了python的curses
標準庫. python curses
標準庫可以用來對終端定制開發(fā)秩冈, 做一些友好的終端命令泛粹。
本腳本不需要安裝其他的庫埃儿, 只依賴標準庫, 在Python2.7 測試通過宴胧, 以下為代碼:
# -*- coding: utf-8 -*-
'''
File Name: mt2.py
Author: JackeyGao
mail: gaojunqi@outlook.com
Created Time: Fri Apr 15 15:52:31 2016
'''
import os, sys
import locale
import signal
import random
import curses
import time
import traceback
locale.setlocale(locale.LC_ALL, '')
code = locale.getpreferredencoding()
stdscr = curses.initscr()
size = lambda: os.popen('stty size', 'r').read().split()
def show_point(str, x, y, colorpair=2):
global stdscr
try:
stdscr.addstr(y, x, str, curses.color_pair(colorpair))
except Exception as e:
pass
stdscr.refresh()
def set_window():
'''''控制臺設置'''
global stdscr
curses.start_color()
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK)
curses.init_pair(4, curses.COLOR_BLUE, curses.COLOR_BLACK)
curses.init_pair(5, curses.COLOR_MAGENTA, curses.COLOR_BLACK)
curses.init_pair(6, curses.COLOR_CYAN, curses.COLOR_BLACK)
curses.init_pair(7, curses.COLOR_WHITE, curses.COLOR_BLACK)
curses.noecho()
curses.cbreak()
stdscr.nodelay(1)
def unset_window():
'''控制臺重置'''
global stdstr
curses.nocbreak()
stdscr.keypad(0)
curses.echo()
curses.endwin()
def signal_handler(signal, frame):
sys.exit(0)
if __name__=='__main__':
signal.signal(signal.SIGINT, signal_handler)
try:
set_window()
while True:
height, weight = size()
y = random.randrange(0, int(height), 1)
x = random.randrange(0, int(weight), 1)
color = random.randrange(1, 8, 1)
show_point('Ooo0oOo', x, y, colorpair=color)
time.sleep(0.01)
except Exception as e:
pass
finally:
unset_window()
注意: 轉載請注明原地址, 首發(fā)平臺http://omem.me, 及作者.