Home > fun, python > Write Python inside Bash

Write Python inside Bash

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
About these ads
Categories: fun, python Tags: ,
  1. RobertX
    April 18, 2013 at 13:33

    Not cheating but not doing what you were asked to do maybe. Totally subjective on the Teacher’s part.

  2. bloo hoo
    April 19, 2013 at 03:34

    Bash has string functions see parameter expansion on the man page

  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 72 other followers

%d bloggers like this: