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

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



On 2007-08-09 09:48:54 -0700, Steve Lamb wrote:
>     The same in Python but with far greater functionality:

and a security hole!

> 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

Imagine a filename contains: ' `some command`

where the command can be a "rm -rf" or something that will send private
data to some remote site...

You can also do such kind of things in Perl, with

  $result = system qw/lame -h -b 160/, $file, $mp3;

and this is much safer!

>     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.

But remember that when you use "system" (available in many languages),
this is a shell that will be started behind, with all the problems of
a shell.

In Perl, when one calls system with more than one element in the list,
this calls execvp instead of doing a conventional "system". Now, I
assume that Python also has some way to call execvp.

> 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.

In portable POSIX sh, yes. But with superior shells such as zsh, this
is trivial. However, for complex transformations, though this can
often be written with few characters, this is completely unreadable!
(See for instance, the advanced zsh completion functions.)

-- 
Vincent Lefèvre <vincent@vinc17.org> - Web: <http://www.vinc17.org/>
100% accessible validated (X)HTML - Blog: <http://www.vinc17.org/blog/>
Work: CR INRIA - computer arithmetic / Arenaire project (LIP, ENS-Lyon)



Reply to: