Python as a scripting language. Alternative to bash script?

D'Arcy J.M. Cain darcy at druid.net
Mon Jun 28 11:29:47 EDT 2010


On Mon, 28 Jun 2010 12:48:51 +0100
Dave Pawson <dave.pawson at gmail.com> wrote:
> I've a fairly long bash script and I'm wondering
> how easy it would be to port to Python.

That's too big a question without seeing more of what your script
does.  I will try to suggest some direction though.

First, if you have a complicated bash script that works, the best
choice may be to just leave it alone.  Think about Python for your next
project instead.
 
> Main queries are:
> Ease of calling out to bash to use something like imageMagick or Java?

You don't need to call bash to call an external program.  Check out the
subprocess module.  If you do need a shell to simplify calling a
program (environment and wild card expansione.g.) don't call bash.
Just use a basic sh.  You won't be using the bash control structures so
keep to whatever is supplied by your OS.  If that turns out to be bash
anyway then no harm.

Another option is to write small Python scripts that you can call from
your bash script.  You can even create them in your bash script.  Here
is a silly example.

uc="import sys
s = sys.argv[1]
print s.upper()
"
...
echo -n "Upper case of $SOMESTRING is ";  python -c "$uc" $SOMESTRING

> Ease of grabbing return parameters? E.g. convert can return both
> height and width of an image. Can this be returned to the Python program?

Just to set the terminology straight, a parameter is what you call the
function with.  The return value is what it returns.  The program
output is what it emits (prints.)

Programs return an integer value.  This is also called the exxit
status.  On success this is 0 but can be otherwise on failure.  You can
use this, for example, with diff to determine if two files differ when
you don't care how they differ.

What you want is the output of the program.  For this you need to
capture the output and parse it.

Look at the subprocess module.

-- 
D'Arcy J.M. Cain <darcy at druid.net>         |  Democracy is three wolves
http://www.druid.net/darcy/                |  and a sheep voting on
+1 416 425 1212     (DoD#0082)    (eNTP)   |  what's for dinner.



More information about the Python-list mailing list