In the previous article of this Python series we shared a brief introduction to Python, its command-line shell, and the IDLE. We also demonstrated how to perform arithmetic calculations, how to store values in variables, and how to print back those values to the screen. Finally, we explained the concepts of methods and properties in the context of Object Oriented Programming through a practical example.

In this guide we will discuss control flow (to choose different courses of action depending on information entered by a user, the result of a calculation, or the current value of a variable) and loops (to automate repetitive tasks) and then apply what we have learned so far to write a simple shell script that will display the operating system type, the hostname, the kernel release, version, and the machine hardware name.
This example, although basic, will help us illustrate how we can leverage Python OOP’s capabilities to write shell scripts easier than using regular bash tools.
In other words, we want to go from
# uname -snrvm

to

or

Looks pretty, doesn’t it? Let’s roll up our sleeves and make it happen.
Control flow in Python
As we said earlier, control flow allows us to choose different outcomes depending on a given condition. Its most simple implementation in Python is an if / else clause.
The basic syntax is:
if condition: # action 1 else: # action 2
- When condition evaluates to true, the code block below will be executed (represented by
# action 1
. Otherwise, the code under else will be run. - A condition can be any statement that can evaluate to either true or false. For example:
1 < 3 # true firstName == "Gabriel" # true for me, false for anyone not named Gabriel
- In the first example we compared two values to determine if one is greater than the other.
- In the second example we compared firstName (a variable) to determine if, at the current execution point, its value is identical to “Gabriel”
- The condition and the else statement must be followed by a colon (:)
- Indentation is important in Python. Lines with identical indentation are considered to be in the same code block.
Please note that the if / else statement is only one of the many control flow tools available in Python. We reviewed it here since we will use it in our script later. You can learn more about the rest of the tools in the official docs.
Loops in Python
Simply put, a loop is a sequence of instructions or statements that are executed in order as long as a condition is true, or once per item in a list.
The most simple loop in Python is represented by the for loop iterates over the items of a given list or string beginning with the first item and ending with the last.
Basic syntax:
for x in example: # do this
Here example can be either a list or a string. If the former, the variable named x represents each item in the list; if the latter, x represents each character in the string:
>>> rockBands = [] >>> rockBands.append("Roxette") >>> rockBands.append("Guns N' Roses") >>> rockBands.append("U2") >>> for x in rockBands: print(x) or >>> firstName = "Gabriel" >>> for x in firstName: print(x)
The output of the above examples is shown in the following image:

Python Modules
For obvious reasons, there must be a way to save a sequence of Python instructions and statements in a file that can be invoked when it is needed.
That is precisely what a module is. Particularly, the os module provides an interface to the underlying operating system and allows us to perform many of the operations we usually do in a command-line prompt.
As such, it incorporates several methods and properties that can be called as we explained in the previous article. However, we need to import (or include) it in our environment using the import keyword:
>>> import os
Let’s print the current working directory:
>>> os.getcwd()

Let’s now put all of this together (along with the concepts discussed in the previous article) to write the desired script.
Gabriel,
Don’t get why this script isn’t working, even after correcting for indentation and adding utf-8 it only runs under IDE’s.
At the console I still get…..
I only code in 2.7 hence the change or omission of line one. I Chmod it and that is the correct path to python2.7.
Yet this is the only python file run at the console that complains like this……….?
The web version does not include indentation where required by python syntax. I added the indentation and got past those errors and then got
the following:
SyntaxError: Non-ASCII character ‘\xc3’ in file uname.py on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
Also it will not run on windows because os.uname not available except on linux.
I got around these errors by using pythonanywhere.com on the web. It ran and was neat but I would think some one at tecmint could help with
the indentation problem and also specify it will not work on Windows.
@Paul,
Thanks for bringing this to our attention. I must confess I never thought I had to state explicitly this would work on Linux only, but we will add that notice as per your suggestion.
@Ravi,
Please add a small note to clarify. As for the indentation, perhaps we will need a different WP plugin. Any ideas?
Program will not run as shown due to no indentation starting with ‘if len(item) < len(headers[index]):'.
@big joe,
It’s possible that the web formatting has damaged the indentation a little. But I can assure you that the program works, as you can see in the screenshots.
I prefer to use subprocess.Popen to execute Linux commands:
uptime = subprocess.Popen([‘uptime’, ‘-s’], stdout=subprocess.PIPE).communicate()[0]
I would also recommend O’Reilly’s “Python for Unix and Linux System Administration”, by Noah Gift & Jeremy Jones. You can easily find .pdfs (if you don’t want to buy it).
@Andy,
While that is true, on a personal note I prefer to keep things as simple as possible. If there is a Python-native way of executing a given command without spawning new process, I’d usually stick with it. Thank you for the book recommendation, I’ll take a look at it.