Python is a great flexible programming language that can be used in many situations. In this tutorial, we will focus primarily on it’s ability to enhance the Unix/Linux shell environment. Typically in Unix we will create “bash” shell scripts, but we can also create shell scripts using python, and it’s really simple! We can even name our shell scripts with the .sh extension and run them as we would run any bash shell script. All we need to do this is to modify the very first line of our file like so:
We can observe here that we are using
!/usr/bin/env python and not
#!/usr/bin/env python instead of the absolute (full path)
#!/usr/bin/python makes sure python (or any other language’s interpreter) is found, in case it might not be in exactly the same location across different Linux- or Unix -like distributions.
#!/usr/bin/python will work on a default Ubuntu system, it is therefore good practice to use
#!/usr/bin/env python instead.
Let us start by creating a very simple python script which will print something for us:
#!/usr/bin/env python # This is my first script. print "Hello Knoldus!"
Before we try to run this script, we will need to make it executable. To do that, we can use the following syntax:
#if our file name is hello.py chmod u+x hello.py
This command basically tells Unix to set the x (executable) flag for the user level access of the file. Now that our script is executable, we can run it using ht e following command:
We will get output as Hello Knoldus! on our console.
Variables are an important part of any program or script. A variable in a python script can be assigned any type of value, such as a text string or a number. In python to create a variable, we simply put in our script:
someVariable = value
Our variable can be anything as long as it only contains numbers, letters and/or an underscore “_”.
Also, a variable name cannot start with a number.
Now let us look how simple it is to use these variables in our scripts:
hello = 'Hello' name = 'Knoldus!' print hello, name
This code will print Hello Knoldus!. As seen above, we use a comma ( , ) to separate the values of variables with a space. If we do not want the values to be separated, we would use the + operator which will concatenate these values and print HelloKnoldus!.
Let us look at another example which will make it more clear as to how these variables are used in our scripts. We will make a script that will tell a user his/her year of birth by taking three arguments – name, age, current year.
#!/usr/bin/env python # Year of birth import sys name = sys.argv age = int(sys.argv) currentYear = int(sys.argv) yob = currentYear - age print 'Hello', name + ', your year of birth is', yob, '!'
We have imported the sys pacakge so that we can access the command line arguments we will provide while executing this script. The arguments are accessed using the sys.argv variable, which is an array containing the command line arguments. The first item in the sys.argv variable (at index 0) is the name of the script being run. The starting index of other arguments is 1. We have also created a fourth variable inside the script which will store the value of year of birth. Be sure to make this script executable before running the script. If we run this script like below:
#filename is years.py ./years.py Knoldus 12 2019
We will get the following output:
Hello Knoldus, your year of birth is 2007!
We can also set the user input in variables like shown below:
#for python 2.7.x name = raw_input('Enter your name: ') #for python 3.x name = input('Enter your name: ')
In order for a script to be very useful, we will need to be able to test the conditions of variables. Most programming and scripting languages have some sort of if/else expression and so does python. Unlike most other languages, spaces are very important when using an if statement. Let’s do a simple script that will ask a user for a password before allowing him to continue.
#!/usr/bin/env python import sys validPassword = 'secret' inputPassword = raw_input('Please Enter Password: ') if inputPassword == validPassword: print 'You have access!' else: print 'Access denied!' sys.exit(0) print 'Welcome!'
Remember that the spacing is very important in the if statement. The indented lines of code after the if condition will run if the condition is true. If the condition is false and there is an else section, then the indented code after the else section will run.
Let us look at different conditional operators we can use:
|!=||not equal to|
|<=||less than or equal to|
|>=||greater than or equal to|
The python class optparse.OptionParser, is a powerful tool for creating options for our script. In our previous example, we just had the user enter two command line arguments to the python script, without specifying which is which. Most users expect to be able to give parameters in any specific order and specify which is which, this can be done in python very easily. Let us look at an example on how to do this:
#!/usr/bin/env python # Years till 100 import sys import optparse parser = optparse.OptionParser() parser.add_option('-n', '--name', dest='name', help='Your Name') parser.add_option('-a', '--age', dest='age', help='Your Age', type=int) (options, args) = parser.parse_args() if options.name is None: options.name = raw_input('Enter Name:') if options.age is None: options.age = int(raw_input('Enter Age:')) sayHello = 'Hello ' + options.name + ',' if options.age == 100: sayAge = 'You are already 100 years old!' elif options.age < 100: sayAge = 'You will be 100 in ' + str(100 - options.age) + ' years!' else: sayAge = 'You turned 100 ' + str(options.age - 100) + ' years ago!' print sayHello, sayAge
This script imports the optparse package in order to make use of the class OptionParser. The OptionParse class will allow us to add options to our script and it will generate a help option based on the options we provide. In this example, we are adding two options: -n (or –name) and -a (or –age). The first parameter to add_option is the short option and the 2nd is the long option, it is quite common in the Unix & Linux environment to add a short and long version of an option. Tthe next optional parameters to the add_option function are dest=, which is the variable name created, help=, which is the help text generated and type=, which gives the type for the variable. By default the type is string, but for age, we want to make it int.
How to access these arguments?
Finally, after adding the options, we call the parse_args function, which will return an options object and an args list object. We can access the variables defined in “dest=” when adding options on the options object returned. So it will have two options, options.name and options.age. If one of the variables wasn’t passed in, we can check by using the “if variableName is None” condition. Then we will load from user input as before.
Now, there are several ways to run this script:
|./hundred.py||Prompts for user and age|
|./hundred.py -n Knoldus||Sets user, prompts for age|
|./hundred.py –name Knoldus||Sets user, prompts for age|
|./hundred.py -a 12||Sets age, prompts for user|
|./hundred.py –age 12||Sets age, prompts for user|
|./hundred.py -a 12 –name Knoldus||Sets age, sets user|
|./hundred.py -n Joe –age 12||Sets age, sets user|
Another thing we can do now is run the help option, by specifying either -h or –help:
This will give the following output and then exit the script:
usage: hundred.py [options] options: -h, --help show this help message and exit -n NAME, --name=NAME Your Name -a AGE, --age=AGE Your Age
The while statement is used when we want to loop while a statement is true. This is the same in many other programming and scripting languages. The body of the loop is the indented, same as in the if/else condition.
Let us look at an example in which we will ask the user to guess s number and check if it is right or not.
#!/usr/bin/env python #guess the number game import random answer = random.randint(1, 10) num = 0 while num != answer: num = int(raw_input('What is the number? ')) if num != answer: print 'Wrong!' print 'Correct!'
This code will repeatedly ask the user ‘What is the number?’ until you get it right.
If the number entered is not equal to the answer generated at startup, it will print the text “Wrong!” and continue the loop, otherwise if you guess correctly, the loop terminates and you see the printed text “Correct!”.
The for loop is used when we want to loop through a list of items. The body of the loop works the same as it does in a while loop. Let’s say that we want to write a program that will validate numbers in a given list. These numbers can be loaded from a file, hard coded, or manually entered by the user. For our example, we will ask the user for a list of numbers separated with spaces and we will validate each number and make sure that it is between 1 and 100. The best way to write a program like this would be to use a for loop.
#!/usr/bin/env python userInput = raw_input('Enter a list of numbers between 1 and 100, separated by spaces: ') nums = userInput.split() for strNum in nums: if not strNum.isdigit(): print 'Not a Number:', strNum elif int(strNum) < 1: print 'Number is less than 1:', strNum elif int(strNum) > 100: print 'Number is greater than 100:', strNum else: print 'Number is valid:', strNum
We have the ability to create functions inside of our script to help with code reuse. Writing the same code in multiple sections of our script can lead to severe maintenance problems. A function is a block of code that can be called from other parts of our script. It can have parameters passed to it as if it were a separate script itself. Let us look at an example on how to make a function. We will be creating a function which calculate the factorial of a number.
#!/usr/bin/env python import sys def fact(n): if n > 1: return n * fact(n - 1) else: return 1 num = int(raw_input('Enter a number: ')) print str(num) + '! =', fact(num)
When our scripts start to grow and our set of functions grow, we will start to notice that many of our functions are related, they work on data that is common between them and they really represent an entity collectively. This is where it is usually a good idea to create a class. We can accomplish this using the class keyword. Let us look how to create and use classes in our scripts.
class Person: def __init__(self, name, age): self.name = name self.age = age def myfunc(self): print("Hello my name is " + self.name) p1 = Person("John", 36) p1.myfunc()
In this example, we have created a class called Person. Then we use the __init__() function which is always executed when the class is being initiated. We use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created. We have also defined a method inside of our class which will print the name of the Person.
One of the powerful features of Python is its ease of use in string manipulation. Operations such as sub-string, split, trim and other common string manipulations are easy under Python. Let us look at an example to better understand it along with it different functions.
#!/usr/bin/env python strUsers = 'python , scala , java , ruby' arrUsers = strUsers.split(',') for user in arrUsers: trimUser = user.strip() trimUserR = user.rstrip() trimUserL = user.lstrip() firstInitial = trimUser[:1] lastInitial = trimUser[1:2] lastName = trimUser[1:] print 'User : \'' + user + '\'' print 'LTrim: \'' + trimUserL + '\'' print 'RTrim: \'' + trimUserR + '\'' print ' Trim: \'' + trimUser + '\'' print 'First Initial:', firstInitial.upper() print 'Last Initial: ', lastInitial.upper() print 'Last Name:', lastName print ''