Introduction to Practical Python Programming
Welcome to my next blog on Python Programming. I am here again to give you some addictive tips on Python. But this time, it’s not based on Hacking, Phreaking or Security Breaking. It is about using python programming for our day-to-day tasks. So, let us start.
What is programming? Don’t worry. I am not here to give you the typical definition of Programming. The part I am about to talk about here today is the use of programming in our day-to-day life and how it helps us automate things.
Python Programming for Non-Engineers
A detailed explanation of python programming for non-engineers:
Everyone in our life is not a software Engineer. But still, everyone has the stuff that they need to deal with. But programming is one thing that can make a lot of things easier. We all have a lot of to-do things in our daily schedule. And instead of we keeping track of that, we can let the machine take care of these things. We can automate our tasks at hand using simple programming. Although there are many commercial softwares of there, we cannot spend money on everything. Also, they won’t be as per our own customized needs. Besides, creating our own program is a totally different level. The best language I can think of as of now is Python programming. Let me tell you how.
Python v/s The world
Python is extremely user-friendly and has a defined way to do things. Unlike ruby, which is another competition for python programming, where ruby is too user-friendly and has a lot of ways to do a single python, python doesn’t offer that. Python programming has indentations and user-readable code.
One of the best example I can think of is this. Every once in a while, or for some people, we have a habit of downloading videos from youtube every now and then. So, we can surely download these videos by downloading some random software from the web and using it. But sometimes, it isn’t that easy. Most softwares on the web are filled with Trojans and viruses.
So, you cannot simply depend on them. God knows what the kind of logic bomb is actually penetrated into that software. So, instead of taking mankind through all this trouble, we have python programming to save ourselves from all these hassles. I found this somewhere on the web a long time ago and have been using it since then. Through this, you can simply download youtube videos with a simple command.
So here is how it goes:
Step 1: Install Python, pip and make sure you select environment variables when installing so you can call Python from the command line from anywhere.
Step 2: Use this command to download the youtube module
>>>pip install youtube-dl
Step 3: Done. That’s it. No step 3. Now, whenever you need to download any video, just simply use this command on the command line and download your video:
>>youtube-dl [OPTIONS] URL [URL...]
Now, you may have an exact idea of what I was talking about. Isn’t this extremely easy rather than downloading any Trojaned software from the internet?
Just note that youtube-dl is a small command-line program to download videos from YouTube.com and a few more sites. It requires the Python interpreter, version 2.6, 2.7, or 3.2+, and it is not platforming specific. It should work on your Unix box, on Windows or on Mac OS X. You can also try >>>youtube-dl –help and check the necessary steps, for example, if you want to download it from https or http or from another port or something like that.
Work: Wishing Happy-Birthday, GEEK Mode ON
If you are not bored of this blog and are still reading this, I will go to a higher level. Let us assume you are a person who is a geek in your group of friends, and they keep telling you how boring you are, and you are investing 16 hours out of your 24 hours in a day on Computer. Then, this is one way to show out how fabulous you can be. Now I will be assuming that you already know bits and bytes of python programming, and I will be proceeding forward.
Let us say you have one of your friend’s birthday this week, and you need to do something in a geeky way that will impress all of your friends. Then, first, let us make a list of what things are there when you go to a birthday party. There will be Cakes, Candles and Birthday songs wishing Happy birthday. So let us create a virtual cake whose shade has an equalizer effect corresponding to the “happy birthday” song that is played in the background. Here, the cake will have candles with flames fluttering randomly.
Also, we will have a fancy display of happy birthday message. The first thing that we need to do is to import some modules to make them work correctly. So, here it goes (and just remember that this is all one piece of code that needs to be placed in one xyz.py file)
>>import scipy.io.wavfile as wavfile >>>import numpy as np >>>import pylab as pl >>>import time >>>import os >>>import sys >>>import subprocess >>>from scipy import mean >>>from random import randint
Now let us write a code for the wave/mp3 file to be run when the code gets executed.
>>>FILE = "Song.mp3" >>>rate, data = wavfile.read(FILE) >>>t_total = len(data[:,0])/rate >>>display_rate = 1500 #number of frames processed in one iteration >>>sample_size = 120 >>>max_display = 90 >>>data_length = len(data) #total number of frames >>>_min = min([abs(x) for x in data[:,0]]) #max amplitude in the wav >>>_max = max([abs(x) for x in data[:,0]]) #min amplitude in the wav >>>correction = 0.645
Now comes the Cake part. Here is the piece of code that I wrote for the cake. You can change the cake’s display char and size depending upon how the cake should look like.
>>>cols = int(subprocess.Popen("tput cols",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE).stdout.readlines()) #columns in terminal >>>display_char = "8" >>>cake_size = 50
Now we need to set the cake on flames so that it looks like a candle is burning.
flame_flutter_rate = 50
FLAMES = [ " . ", ". ", " ." ] current_flame = ""
os.system("tput civis") #hide cursor
Now, if you are on a mac, you may need to open iTunes or some other player to run the song. So, if you are on a mac, then uncomment the below os.system command code. (Just simply remove the hash# tag)
for _f in range(data_length/display_rate):
# fluttering effect to candle flames
if _f%flame_flutter_rate == 0:
current_flame = (" "*(cols/2 - cake_size/2))+((" "+FLAMES[randint(0,2)]+" ")*(cake_size/5)) print current_flame
print (" "*(cols/2 - cake_size/2))+(" | "*(cake_size/5))
# cake top layer print (" "*(cols/2 - cake_size/2))+("-"*cake_size)
bucket =  mug = 
# mug contains the current frame samples (absolute values) of given sample_size # average of mugs are put into bucket
for value in data[:,0][_f*display_rate+1:(_f+1)*display_rate]: mug.append(abs(value))
if len(mug) == sample_size:
bucket.append(mean(mug)) mug = 
bucket = [ (float)((x - _min) * max_display)/(_max - _min) for x in bucket ]
# print the equalizer from the bucket for value in bucket: print (" "*(cols/2 - cake_size/2))+"| "+("8"*(value%(cake_size-2)))+(" "*(cake_size-value-2))+"|"
# bottom crust of the cake print (" "*(cols/2 - cake_size/2))+("-"*cake_size)
# print happy birthday message os.system("figlet -c -f small Happy Birthday Chetan!")
# sleep to match with the audio
NOTE: a correction has to be multiplied to sleep time
This is because of several factors like time taken to wake from sleep, type of terminal used..etc
CHANGE THE VALUE OF correction TO FIT YOUR NEED
time.sleep(((float)(display_rate * t_total) / data_length)*correction)
# clear screen if _f != data_length/display_rate-1: os.system("clear")
Now, these are a few examples that I do when I get bored. Just change the name, make a few changes for every other person. So, this not only makes python programming interesting, but it can also do your day to day tasks.
You can even create your own to-do list or a notepad or something like that. Now you may think that there are ‘n’ number of programs out there that do the same, so why write your own one. The reason for that is customization. When you buy or download software, you don’t know what the source code is, or if you need some of your own customizations, you may even need to purchase the software. But python programming is so extremely easy to understand and write that you don’t need to buy anything.
Besides, to tell you the truth, I first started to automate my daily tasks using python programming, but later I got so interested that I started learning everything related to that, and now my job profile is the same; to create programs in Python.
That would be the end of this blog, but before I end this, I will give you some points so that you can go and check some cool automation stuff that people have done with python, and I am sure that you will be surprised to see what people have done with simple programming. There is also a book named as “Automating boring stuff with Python”. Make sure to check that.
So, here goes my list:
- Renaming multiple files with a simple code (I am talking about files more than 100,200 or even 1000)
- Automating scripts at work (If you are a System Engineer)
- Creating an RSS reader (Cause using a built-in one is too mainstream)
- Creating a Password protected Phonebook (extremely simple)
- Creating a Password Protected Notepad to save passwords and personal docs(including images and docs)
- Downloading mp3 files by using smart search (Downloading mp3 files with similar names directly and randomly from the web)
Here are some articles that will help you to get more detail about Practical Python Programming, so just go through the link.