Python as a scripting language. Alternative to bash script?
Dave Pawson
dave.pawson at gmail.com
Mon Jun 28 14:02:08 EDT 2010
On 28 June 2010 18:39, Michael Torrie <torriem at gmail.com> wrote:
> 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.
Thanks Michael.
>
>> 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.
I'm using xml quite a bit and tried xmlsh which does the job but has
what I think of as irregular syntax?
Bash is fine for smaller scripts, but I had to be really careful by
the time I got to around 1200 loc. Hence my preference for Python.
>
> 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.
I kept thinking that.. Then I had to use Java/Python for some plain
old calculations, so it kept nagging me that a cleaner approach
would be a single language.
> 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/
Thanks for the reference.
I'm nearly there with the mix of return codes and output values,
using subprocess.
p1 = subprocess.Popen(['identify', '-format' , '%[fx:w]' , f ],
stdout=subprocess.PIPE)
resp1= p1.communicate()
#print dir(p1)
p2 = subprocess.Popen(['identify', '-format' , '%[fx:h]' , f ],
stdout=subprocess.PIPE)
resp2= p2.communicate()
if (p1.returncode or p2.returncode):
print "Error ",p1.returncode
sys.exit(2)
else:
width=int(resp1[0])
height=int(resp2[0])
print "Height %s, width %s " % (height, width)
Not happy with the error handling yet, but this was the bit
that I thought I'd struggle with.
regards
--
Dave Pawson
XSLT XSL-FO FAQ.
Docbook FAQ.
http://www.dpawson.co.uk
More information about the Python-list
mailing list