Python as a scripting language. Alternative to bash script?
Michael Torrie
torriem at gmail.com
Mon Jun 28 13:39:28 EDT 2010
On 06/28/2010 05:48 AM, Dave Pawson wrote:
> Main queries are: Ease of calling out to bash to use something like
> imageMagick or Java? 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? Can Python access the exit status of a program?
Sure. I've created a module called runcmd that does 90% of what I want
(easy access to stdout, stderr, error code). I've attached it to this
e-mail. Feel free to use it; this post puts my code into the public domain.
> I'd prefer the advantages of using Python, just wondering if I got so
> far with the port then found it wouldn't do something?
Python really isn't a shell scripting language. So there are things
that Bash does much better, such as spawning processes and piping them
together. I've tried over the years to create a pythonic library that
would let me do that, but haven't found a good syntax that I like.
It turns out, though, that much of what I use piping for in Bash is to
run external processes to do things that I could use python modules for.
For example, I typically pipe stuff to cut a lot to get certain fields.
For example:
ps ax | cut -c1-5
In python I could simply take the output of "ps ax" and use python's
own, superior, cutting routines (using my module):
(err, stdout, stderr) = runcmd.run( [ 'ps', 'ax' ] )
for x in stdout.split('\n'):
print x.strip().split()[0]
Sure it's a couple more lines in this case, but in other cases, python's
abilities make it simpler than bash. A great document on how you can
exploit python's abilities (particularly generators) to replace bash
pipelines is here: http://www.dabeaz.com/generators/
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: runcmd.py
URL: <http://mail.python.org/pipermail/python-list/attachments/20100628/f2eb6c1b/attachment-0001.ksh>
More information about the Python-list
mailing list