Posts Tagged ‘programming’

Hi guys, this is a post on creating a simple text mode menu in Python 2.7.x. Hope this helps! Below is the output of the sample menu that we will be creating:

Sample Menu

------------------------------ MENU ------------------------------
1. Menu Option 1
2. Menu Option 2
3. Menu Option 3
4. Menu Option 4
5. Exit
Enter your choice [1-5]: 

Here we have a function print_menu() which is used only to print the menu and the options available. This function does not take any inputs.

The source we have here creates a menu with 5 options with the 5th option to exit the menu.

Here, we create a Boolean variable named “loop” and set its value to “True“. Then we create a while loop which will run until the value of “loop” is “False”.

And within the while loop, we call the function print_menu() in which the user is presented with a menu and the list of options. We now request the user input and store it in a variable named “choice” [NOTE: The input must be a number and not any character or else it will through a error].

Now, we use create if statements to check the value of choice. For example: the first if statement checks if choice==1 and if it prints “Menu 1 has been selected”. Similar, We make use of elif statements to check other values of choice.

And when choice==5, we change the value of “loop” to “False” , which will end the while loop as it will only run when the value of “loop” is “True“.

Finally, for all other numbers other than 1,2,3,4 and 5, we simply print and error message and requests the user to enter a valid input and to try again.

Source Code:

## Text menu in Python
def print_menu():       ## Your menu design here
    print 30 * "-" , "MENU" , 30 * "-"
    print "1. Menu Option 1"
    print "2. Menu Option 2"
    print "3. Menu Option 3"
    print "4. Menu Option 4"
    print "5. Exit"
    print 67 * "-"
while loop:          ## While loop which will keep going until loop = False
    print_menu()    ## Displays menu
    choice = input("Enter your choice [1-5]: ")
    if choice==1:     
        print "Menu 1 has been selected"
        ## You can add your code or functions here
    elif choice==2:
        print "Menu 2 has been selected"
        ## You can add your code or functions here
    elif choice==3:
        print "Menu 3 has been selected"
        ## You can add your code or functions here
    elif choice==4:
        print "Menu 4 has been selected"
        ## You can add your code or functions here
    elif choice==5:
        print "Menu 5 has been selected"
        ## You can add your code or functions here
        loop=False # This will make the while loop to end as not value of loop is set to False
        # Any integer inputs other than values 1-5 we print an error message
        raw_input("Wrong option selection. Enter any key to try again..")

Feel feel to leave a comment if you have any queries or want to reach out to me. You can also Follow/Subscribe to my blog to get future blog posts! Happy Bloggin! 🙂


Cleaning the Prefetch folder in Windows OS helps increasing the performance of the system. You can clean your Prefetch files manually by going to the X:\Windows\Prefetch\ folder and deleting all the files in that directory. This can be time consuming and today I will be introducing the “os” module in python and show you how to create your own prefetch cleaner program so that you clean the prefetch folder for you in a single click.

So, basically the prefetch cleaner simply changes the current directory to your Prefetch folder(X:\Windows\Prefetch\ , where X is your drive where your Windows is installed) and gets the list of files in that folder and deletes each one of them.

Assuming you have python installed in your computer(else read my other blog post on how to install python here). Now, import the “osmodule using the following code:

import os

The next thing you need to do is to change your current working directory to the prefetch directory. This can be done using the function called “chdir(path)” in the os module. The parameter path is going to be the prefetch directory which in my case is “C:\WINDOWS\Prefetch“. So, we we use the following line of code:


Now, you need to get the list of all the files in that directory .This can be done using the function listdir(path) which returns a list containing the list of files in that directory and storing the result to a variable( For example: prefetch):


Now, since we have the list of files,  to delete each file in the list you can simply use a for loop to traverse through each element in the list and call a function that deletes the file.  Now, we create a function called del_file(name) which takes takes a “filename” as parameter and deletes the file. We can delete a file using the function os.remove(filename) . The function can be implemented as:

def del_file(name):
    print i, " Deleted"

Now, finally you need to just create a for loop to traverse through all the elements(which are filenames of each file in the directory) in the variable prefetch and call the function del_file(i).

for i in prefetch:

Complete source code of the Prefetch Cleaner:

# Prefetch Cleaner
import os

def del_file(name):
    print i, " Deleted"

prefetch=os.listdir("C:\WINDOWS\Prefetch") # Change letter "C" to your OS drive letter

for i in prefetch:

print "Prefetch Cleaning Complete "
raw_input("Press Enter to exit..")

It is recommended that you close all media players such as VLC or Windows Media Player etc before you run your prefetech cleaner program. Happy Coding!


The basic idea to check if a port is open is to connect to the host at that particular port and if the connection was successful , then it means the port at which we tried to connect is open otherwise it is not open.

The first thing we do is to ask the user the IP address and the range of ports we need to scan (Alternatively you can predefine them in the source). Then we create a loop within the range of the given ports, and for each value of the port in the loop we try to connect to the current value port at the specified host, and if the connection was successful, we print that that particular port is open. And after every check we close the created socket.

# Port Scanner
from socket import *                          # Imports socket module
ip=raw_input("Enter IP to scan : ")           # Asks user to enter IP address
start=input("Enter starting port number : ")  # Asks user to enter starting port number
end=input("Enter ending port number : ")      # Asks user to enter ending port number
print "Scanning IP: " , ip
for port in range(start,end):                 # For loop from starting to ending port
    s=socket(AF_INET, SOCK_STREAM)            # Creates a socket s
    if(s.connect_ex((ip,port))==0):           # If connection to port was successful,then returns 0
        print "Port " , port, "is open"       # Prints open port
    s.close()                                 # Closes socket s
print "Scanning completed !! "

If you have any sort of queries , feel free to ask. Thank you! Happy Coding!


There are many ways in which you can get help with commands. One way of getting help with a command is by using the “man” command which provides the manual page.

For example, if you want to know more about how to use the “cp” command, you can read its manual page by using the following command in the terminal:

# man cp

Another way is to use the “–help” command. This will give you a brief outline of the arguments that can used with the command.

For example, if want to find what all options or parameters can be used along with the command “mv” or remove command, you can use it by typing the following:

# mv –help



In the server side, we have to create a socket, Bind the socket to the address and port, and then set it to listening state and waits for the client to connect. When a client requests a connection, the server then accepts the connection.

Make sure you opened up two Python Shells (or Python IDLEs) so that you can run both the client and server.

This is a very basic program that sends a string of data from the server to the client and displays it to the client.


# TCP Server Code

host=""			    # Set the server address to variable host
port=4446 				    # Sets the variable port to 4446
from socket import *	 		    # Imports socket module


s.bind((host,port))     		    # Binds the socket. Note that the input to
                                            # the bind function is a tuple

s.listen(1) 		        	    # Sets socket to listening state with a  queue
                                            # of 1 connection

print "Listening for connections.. "

q,addr=s.accept()			    # Accepts incoming request from client and returns
                                            # socket and address to variables q and addr

data=raw_input("Enter data to be send:  ")  # Data to be send is stored in variable data from
                                            # user

q.send(data) 		        	    # Sends data to client


# End of code


TCP Client

In the TCP Client, we need to create the socket first, then connect to the server by using the socketname.connect((ipaddress,port)) . Then you need to receive the data which is send from the server, this is done by using the function socketname.recv(size)

# TCP Client Code

host="" 			# Set the server address to variable host

port=4446 				# Sets the variable port to 4446

from socket import *			 # Imports socket module

s=socket(AF_INET, SOCK_STREAM)		# Creates a socket

s.connect((host,port))			# Connect to server address

msg=s.recv(1024)			# Receives data upto 1024 bytes and stores in variables msg

print "Message from server : " + msg

s.close()                            # Closes the socket
# End of code

Happy Coding!