How to re-write this bash script in Python?

Grant Edwards invalid at invalid.invalid
Fri Jul 31 16:26:28 CEST 2015

On 2015-07-31, Chris Angelico <rosuav at> wrote:

> There are two basic approaches to this kind of job.
> 1) Go through every line of bash code and translate it into
>    equivalent Python code. You should then have a Python script which
>    blindly and naively accomplishes the same goal by the same method.

In my experience, that works OK for C (with a little post-translation
tweaking and re-factoring).  But, it's a pretty lousy method for bash
scripts.  There are a lot of things that are trivial in Python and
complex/hard in bash (and a few vice versa), so a direct translation
usually turns out to be a mess.  You end up with a lot of Python code
where only a couple lines are really needed. You also end up doing
things in a bizarre manner in Python because the simple, easy, right
way wasn't supported by bash.

> 2) Start by describing what you want to accomplish, and then
>    implement that in Python, using algorithmic notes from the bash code.
> The second option seems like a lot more work, but long-term it often
> isn't, because you end up with better code.

And the code works. :)

For bash, I really recommend 2)

Grant Edwards               grant.b.edwards        Yow! GOOD-NIGHT, everybody
                                  at               ... Now I have to go
                                administer FIRST-AID to my
                                                   pet LEISURE SUIT!!

More information about the Python-list mailing list