[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: bash vs. python scripts - which one is better?

Manon Metten wrote:
> - Which one is easiest to learn?

    Between Bash and Python, Python.

> - Which one is more powerful?


> - Can I execute /bin commands from within a python script
>   (something like mkdir or ls)?

    Yes, though for those examples you don't need to.  The os library gives
you the ability to do the above and much more.  There is also a module called
shutil which provides the basic functionality of different shell utilities
available natively in Python.  I have rarely had to resort to calling
something in shell to do anything shell can do.

> Or should I learn bash scripting anyway?

    Learn enough to be able to parse it and convert it to your language of
choice.  There are exceptions, of course, but by and large it has been my
experience that any place you're required to use shell Python is also
available and a far better choice.  As an example here is the shell example
given earlier:

for FILE in *.wav; do lame -h -b 160 "$FILE" "$FILE.mp3"; done

    The same in Python but with far greater functionality:

import os
for file in os.listdir('.'):
    root, ext = os.path.splitext(file)
    if ext.lower() == 'wav':
        mp3 = root + '.mp3'
        result = os.system("lame -h -b 160 '%s' '%s'" % (file, mp3))
        if result:
            print '%s not converted' % file

    Longer, yes.  Easier to follow?  Most certainly.  Superior, no doubt.  The
shell example would miss WAV, Wav, wAv, etc.  Secondly the only place we need
to escape the variable is when we need shell to do some work, namely the call
to lame.  Finally we don't end up with '.wav.mp3' files all over the place.
We can check the results easily and handle failures gracefully.  Can all of
that be done in shell?  Certainly.  Is it worth doing in shell?  Not hardly.

    I don't use shell even for one liners these days because of the errors
introduced by globbing and spaces in filenames.  Yes, if one keeps them in
mind when writing shell then they aren't /too/ much of a problem.  But in a
proper language like Python (Perl, Ruby, take your pick) one doesn't have to
keep it in mind *at all* except when dealing with shell.  Not to mention the
native methods for dealing with some issues, like stripping the extension from
the root of a file, are trivial in Python while an exercise in frustration in
pure shell.

Reply to: