Wednesday, July 1, 2009

Python and Bash slow print function

I always liked to toy with slow printing terminal functions that have a small delay between each character (a bit Matrix style). Here is the Python 3 version:

Syntax highlighted version here.


#! /usr/bin/env python3

import os, sys, time

def dprint (message, delay=0.1):
"""
Prints message with delay between each character.
"""
for char in message:
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(delay)

if __name__ == '__main__':
"""
Demonstration logic.
"""
os.system('clear')
dprint('This message is printed slowly and demonstrates the slow\n' +
'print function.')



Below is an older version written as a bash shell script which does the same.

Syntax highlighted version here.


#! /bin/bash

mm_decho ()
{
local i stepping
stepping="0.01"

# When first argument is empty or not given, it just echoes a new line
# and leaves.
if [ ! "$1" ]; then
echo
return
fi

# If a second argument is given (delay stepping), check it for validity
# (if it is a float) and set stepping according to the argument.
if (( $# > 1 )) &&
[[ ($2 = $(echo $2 | grep -oE '[[:digit:]]')) ||
($2 = $(echo $2 | grep -oE '[[:digit:]]+\.[[:digit:]]+')) ]]
then
stepping="$2"
# In case the previous test failed, but we have a second argument,
# meaning it is invalid, just print the message, complain a bit and then
# quit the function with false.
elif (( $# > 1 )); then
echo "$1"
echo ".! mm_decho() oops: second argument is invalid!" 1>&2
echo ".! must be /float but is: \"$2\", leaving function.." 1>&2
return false 2>/dev/null
fi

# Do delayed printing of first input argument. Calculate the
# length of first arg. and substract one. Then make it a /for/
# sequence going through all the characters of the string,
# printing these and wait the delay stepping time.
for i in $(seq 0 $((${#1}-1))); do
echo -n "${1:$i:1}"
sleep $stepping
done
echo
}


mm_decho "Should be ok, default.."
mm_decho "Should be ok, costume stepping.." "0.05" "some more arg"
mm_decho "Should be ok, costume stepping.." "0.05"
mm_decho "" "0.3"

No comments:

Post a Comment