Archive

Archive for November, 2012

Write Python inside Bash

November 24, 2012 2 comments

Problem
You want to embed Python code inside a Bash script.

Solution
Here is a possible solution:

#!/usr/bin/bash

# name.sh

# Example:
# Write a bash script that has one parameter: your name.
# It prints every second character of your name.

TFILE="`basename $0`.$$.py"

cat <<END >$TFILE
#!/usr/bin/env python

import re
import sys

bash_name = re.sub(r'\.\d+\.py', '', sys.argv[0])

def process(s):
    print s[::2]

def main():
    if len(sys.argv) > 1:
        process(sys.argv[1])
    else:
        print "Usage: {0} <parameter>".format(bash_name)

if __name__ == "__main__":
    main()
END

chmod u+x $TFILE
./$TFILE "$@"
/bin/rm $TFILE

Usage:

./name.sh Your_Name
Yu_ae    # output
Advertisements
Categories: fun, python Tags: ,

Handle CTRL+C in your script

November 21, 2012 Leave a comment

Question

In your script you want to handle the SIGINT signal, i.e. when the user wants to stop the script with CTRL+C, you want to call a function to handle the situation.

Answer

Here is an example:

#!/usr/bin/env python

import signal
import time

def sigint_handler(signum, frame):
    print 'Stop pressing the CTRL+C!'

signal.signal(signal.SIGINT, sigint_handler)

def main():
    while True:
       print '.'
       time.sleep(1)

##########

if __name__ == "__main__":
    main()

Now the script is immune against CTRL+C. You will have to kill it (“kill <PID>”) if you want to stop it.

If you want protection against “kill <PID>”, handle the SIGTERM signal too :)

Roman numbers to decimal

November 8, 2012 Leave a comment

Problem
You want to convert Roman numbers to decimal and decimal numbers to Roman numbers.

Solution
I found a module for this task called romanclass (http://pypi.python.org/pypi/romanclass).

I wrote a simple wrapper around it, available here.

Categories: python Tags: , ,