Wednesday, February 18, 2015

Replacing Bash with Python?

Since I'm very new to Python, but already familiar with Bash, I asked google search if it is a good idea to use Python instead of Bash.

It seems that generally Bash can be replaced with Python, integrating Bash and Python functionality. It is generally said that programming in Python is easier and more convenient than programming in Bash.
However, there are cases when it is rationally recommended to stick with Bash instead of Python:
"I agree that bash's syntax is pretty awful except for the one thing it does very well, which is execute programs (and pipe their output into other programs). Its syntax is very optimized for that. And yes, implementing find(1) yourself in Python is more work than just using find directly. :)"
When migrating from Bash to Python while still learning Python, it is recommended to do it slowly, taking one step at a time, replacing only those pieces in your bash script, that are easier to do in Python than in Bash:
  1. Replace AWK and PERL with Python. Leave everything else alone.
  2. Look at replacing GREP with Python. This can be a bit more complex, but your version of GREP can be tailored to your processing needs.
  3. Look at replacing FIND with Python loops that use os.walk. This is a big win because you don't spawn as many processes.
  4. Look at replacing common shell logic (loops, decisions, etc.) with Python scripts.
RedHat Magazine has an enjoyable article by Noah Gift about working your way through the learning process. When reading it, the whole migration seems so easy...

It is also a good idea to get familiar with some Python modules that can help in replacing Bash with Python:
  • subprocess - an implemented module
  • sh - a non implemented module
  • plumbum - a library for shell script-like programs in Python

There is also an interactive Python shell that might replace the linux shell for you:

No comments:

Post a Comment