Search

Python script to create a matrix on the linux terminal

Use the following script to create a matrix like background on the terminal.
import sys, termios, atexit
from select import select
import curses as cur
from curses import wrapper
import time
import datetime
import random
# save the terminal settings
fd = sys.stdin.fileno()
new_term = termios.tcgetattr(fd)
old_term = termios.tcgetattr(fd)
# new terminal setting unbuffered
new_term[3] = (new_term[3] & ~termios.ICANON & ~termios.ECHO)
# switch to normal terminal
def set_normal_term():
termios.tcsetattr(fd, termios.TCSAFLUSH, old_term)
# switch to unbuffered terminal
def set_curses_term():
termios.tcsetattr(fd, termios.TCSAFLUSH, new_term)
def putch(ch):
sys.stdout.write(ch)
def getch():
return sys.stdin.read(1)
def getche():
ch = getch()
putch(ch)
return ch
def kbhit():
dr,dw,de = select([sys.stdin], [], [], 0)
return dr
if __name__ == '__main__':
atexit.register(set_normal_term)
set_curses_term()
stdscr = cur.initscr()
cur.start_color()
cur.noecho()
cur.cbreak()
cur.curs_set(0)
stdscr.keypad(True)
cur.init_pair(1, cur.COLOR_GREEN, cur.COLOR_BLACK)
x=datetime.datetime.now()
cols=lines=0
cols=(cur.COLS)
lines=(cur.LINES)
count=10
x=random.choice([0,1])
stdscr.nodelay(True)
while 1:
if kbhit():
ch = getch()
break
for x in range(0,cols-1):
for y in range(0,lines):
data=random.choice([0,1])
stdscr.addstr(y,x,str(data),cur.color_pair(1))
stdscr.refresh()
print("done")
cur.nocbreak()
stdscr.keypad(False)
cur.echo()
cur.curs_set(1)
cur.endwin()
Save the script as matrix.py, open the terminal and run the script using

You should see an output as shown in the video below, hit any key to stop the matrix.

Thanks to the following link for the code of kbhit


1 comment: