Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to execute command at shell from Python

📅 2014-Nov-20 ⬩ ✍️ Ashwin Nanjappa ⬩ 📚 Archive

There are many operations at the shell that need a bit of looping or automation. You can learn programming in the language of the shell you use to achieve this. Since I know a bit of Python, I prefer to use it for running quick commands at the shell. The call to execute a command at the shell is os.system.

I typically use this call to automate repeated commands that I want to run at the shell. For example, I open a Python interpreter from your shell and type:

import os

for i in range(100, 200):
    s = "montage foo-" + str(i) + ".png bar-" + str(i) + ".png -tile 2x1 foobar-" + str(i) + ".png"
    os.system(s)

This quickly makes pairs from two sets of 100 images I have, puts them together and creates a new set of 100 images. Pretty sweet to automate operating on 100 images with just a few lines of code! 😊

Tried with: Python 2.7.6 and Ubuntu 14.04