Showing posts with label Python tutorial. Show all posts
Showing posts with label Python tutorial. Show all posts

Tuesday, September 1, 2015

Python Socket - Some useful Functions

 I have shown you how to write basic socket programming and also how to create a simple client-server model for socket programming in my website http://pythonbeginner.in/socket-programming-in-python.
Now lets see some of the common socket modules which we skip sometimes but they are useful enough. One of them is socket.gethostbyname().this particular function will give us the ip address of a domain name. Lets see by an example  -

>>> import socket
>>>print (socket.gethostbyname("www.google.com"))
216.58.196.100

So, if you want to know the ip address of a certain domain, you can always try this option.

Other function is the opposite of this function; socket.gethostbyaddr() will give us the domain name of a ip address (if domain to ip map is available). Lets see that through an example  -

>>> print (socket.gethostbyaddr(216.58.196.100))
('maa03s19-in-f4.1e100.net', ['maa03s19-in-f100.1e100.net'], ['216.58.196.100'])


Now if you want to see the name of the domain and the port together you can use this  -

>>>   print (socket.getnameinfo(('216.58.196.100',80),0))
('maa03s19-in-f4.1e100.net', 'http')
You can change the value of 0 in the second element of the passed tuple and see what happens.

Thursday, August 13, 2015

Database Programming Python Tutorial, Creating a Table and Inserting Values in It with Python

In python programming the module named sqlite3 or _MySQL can be used to database operations(Along with many others). The basic principal of writing database program is same for more or less every database in python. You have to create a way to communicate with the database and then execute the SQL queries through python. Lets see it by an example - 

import sqlite3 as db
conn = db.connect('test1.db')
cur=conn.cursor()

cur.execute('drop table if exists Employee-info')
cur.execute("CREATE TABLE
Employee-info (uniqueid integer primary key AUTOINCREMENT,name TEXT,dept TEXT, address TEXT,profession TEXT,status TEXT DEFAULT 'Single');")

conn.commit()

The above code imported the sqlite3 module and renamed it as db.We have made a connection to the database with the name test1.db, if it is not present there the said line will create one db in the current working directory. (If you don't know how to find current working directory then see here.)

Now , the next line created a cursor for the connected database. You can say the cursor is the way of operating different commands to the database in SQL mode. In the next line you can see the cur.execute() statement executes a SQL command to the database. It simply find a previous table named Employee_Info and deletes it, so that we can create a table with the same name.

In the next line we created table with required value, Again I have used SQL command within the cur.execute() to create the table. The table is created with primary key uniqueid which will be automatically incremented every time when a new entry to the database will occur.

Now as we have a basic understanding of creating the database and a table, lets try to insert some value in it. Do you know what is the basic command in SQL for inserting values into database ?
 It is - 
INSERT INTO Employee_info  VALUES ('name','dept','address',...);  
In python we can do the same by using the cur.execute again but with certain modifications. For this example lets do it the following way, there are more way which I will discuss later - 
rowdata=('Dhruba','IT','DNK','IT','S')
cur.execute('insert into troublebook(name,dept,address,profession,status)\ values(?,?,?,?,?,?)',rowdata)  
conn.commit()
This will insert values in the database. The rowdata contains all the needed values, so the program will run without a problem. We can executemany by implying cur.executmany() with rowdata holding more rows of values .

Please visit http://pythonbeginner.in for more topics.

Tuesday, August 11, 2015

A Touch of Python CGI Programming

Python CGI( Common Gateway Interface) is a server side script which help us to write server side auto generated html page. The utility is that with CGI programming you can generate page depending upon the input to the webpage. Before I dig into Python CGI, I need to introduce you to a little bit of html -

<html>
<title>Intro to HTML</title>
<body>This is the body of your webpage</body>
</html>

Write the above line in a text editor, name it something.html and double click it. It will open in your favorite browser and show the lines in between the body and title tag. This is called a html page, please visit some online tutorial for more details.

Now lets write a python cgi file. To run cgi script you have to configure or download servers which supports python cgi scripting. I recommend you to use xampp as it  is easy to use and not so complicated to configure. Download xampp and install it.

The next thing is to open the cgi-bin folder in the c:\xampp folder. You will be writing all your cgi scripts in the folder. So lets create a file and name it 'firstcgi.py'. Write the following in the file and save it -

#!/usr/bin/python """(In case of windows #!/Python27/python probably, you need to check your python installation path to be sure)"""
import cgi
import cgitb
print "content-tpe:text/html\r\n\r\n"
print ""
print """
<html>
<title>Intro to HTML</title>
<body>This is the body of your webpage</body>
</html>
 """
 To run the cgi file you either need to go to the directory of the cgi file and run python CGIHTTPServer or simply run the webserver and type the path http://localhost/cgi-bin/firstcgi.py, see if it runs or not. You will probably find some errors or some 500 error. Why?
A few thing to remember before writing CGI Script  -
  •  Always make the cgi script file executable by going to the properties of the file in case of windows and for linux change it by chmod a+x filename command.
  • You need to change the ownership to  the current user of the file. chmod 775 is a better option for python cgi file, for windows user make it read and writable.
  • Always store the file in cgi-bin folder, it is an obligation of writing cgi script.
  • Make sure you run the CGIHTTPServer command from the same directory where cgi-bin folder is located.     
  • The path to the python executable file is not optional, always start cgi program with the #! followed by python path
 Now check your program in your browser , you will see the same output as the previous html file but only it is generated by python cgi script. What is the use? We will see in next entry .

 

Friday, July 31, 2015

Python Tkinter Button,Label and Text Example

Python Tkinter has all the facilities a desktop GUI application will need, we will discuss button, label and text maker in Tkinter here. The generic declaration format to create  the three is like below -

    label=Lable(mainwindow,option=......)
text=Text(mainwindow,option=......)
         button=Button(mainwindow,options=.....)

Button is the name of the function/class you can see from the declaration. In this we have created a Button in the mainwindow e.g root I we have created in my previous blog.Options can be anything like fg - Normal foreground, bg - background ,font - text font used in the button, and many more like height, width , command,text and many more.

Lets see the creations of those with example -

from Tkinter import *
import tkMessageBox

class JustExample:
        def __init__(self,master):
                button=Button(master,text="Click Me",command=self.clicked).pack()
                text=Text(master,fg="blue",bg='beige').pack()
                label=Label(master,text="The Label").pack(
side=TOP)
        def clicked(self):
                tkMessageBox.showinfo("Hello Python","Nearly There")
               
root=Tk()
c=JustExample(root)
root.mainloop()


I created a class to show the procedure of creating button,label and text box. Besides importing the Tkinter I have also imported tkMessageBox module.The JustExample class is initialized with the master window or root window, and then I have cretaed one button with text 'click me' and the command which called the function in the class clicked(). You can see the text option bg and fg which says you will write blue text in beige background. The label has the option pack with side=TOP which says it will be on the top of the window. The output will look something like below -






Saturday, July 18, 2015

Python File I/O

Python comes with easy to use inbuilt functions for handling files. Like other programming practices files can be opened in read , write and append mode in python. There are also binary read and write mode and also r+ mode available. I will go through each of them.

To open a file , you have to write -
   f=open('filename','mode')
The default mode  in python is 'r' mode i.e. if you don't supply anything to mode option it will open the file in read mode. In read mode you can only read the file, you can not modify or erase the file content.
In write mode you can create a file. It erases a file if it has a same name. So handle it carefully, you don't want to delete important file with same name.
Append mode helps to write something in an already written file. It appends the new data in the file without deleting previous content.
In r+ mode you can open the file in both read and write mode altogether.

Let's understand a file operation by example.

This python program examples will find out share price of your favorite share and make a file consisting of all the share prices in different interval of times.

import urllib,time
f=open('mcxwholedayprice.txt','w')
s=str(time.strftime("%H:%M:%S"))
(hour,minutes,seconds)=s.split(':')
hour=int(hour)
curhour=0
while curhour<hour+12:
      
        page=urllib.urlopen("https://www.google.com/finance?q=NSE%3AMCX&ei=eIqoVcGIEsuYuATZpZ3gBw")
        text=page.read().decode("utf8")
        #print text
        text=text.lstrip()
        where=text.find("ref_272295776418103_l")
        #print where
        a="The MCX Share Price ",text[where+23:where+31]
        f.write(str(a))
        time.sleep(900)
        s=str(time.strftime("%H:%M:%S"))
        (curhour,minutes,seconds)=s.split(':')
        curhour=int(curhour)
f.close() 


Take a close look at the program above. The program imports two modules urllib and time. urllib is needed to open a website page from given url. First of all I needed to find the share price of my favorite share in google finance and write the link in the urlopen() function.Then I call time.strftime() to get the time now in a desired format and get the hour out of the format by s.split()-previously discussed in string section.
The while loop will run for 12 hours and record all the data needed to the variable a. The variable then converted to string and then written to the file we have opened in write mode. Finally it closes the file.
You can do it in your way, there are redundant line for better understanding and they can be easily removed. Can you find them out?

The other operation is read () method in python file handling. You have written a file in the previous program. To read the content of the file you need to write the following  -

f=open('mcxwholedayprice.txt','r')
print f.read()
f.close()

You can give arguments in read() function too.e.g. f.read(20) - Reads the twenty characters of the file.
f.readline() - Used to read single line of the file.
f.readlines() - Read the file line by line formatted as a list.
f.tell() - Tell the current position of file head or handler.
f.seek(n) - Goes direct to nth character of the file.



Visit my website for more free contents and more programs on files at http://pythonbeginner.in
and learn python.

Tuesday, July 14, 2015

Introduction to function - Python

Function - if you are familiar with any programming language, you should know what the function is. It is a process of minimizing code repetition. Of we have to do something frequently in a program we write the code snippet as function and call out when necessary.
Python function is declared by def and then followed by name of the function and parameters which the function needs, then followed by colon.
def add (a,b):
   c=a+b
   return c
while True:
   a=int(raw_input("please enter the first value or press x to quit"))
   b=int(raw_input("please enter the first value  or press x to quit"))
   if a=="x" or b=='x':
      break
   c=add(a,b)
   print c
  

Can you find the fault in the program? the a=='x' can not be executed as the conversion of x into integer can not be possible. So, the idle throws exception but also get out us of the loop.

you can also give default value to function input values. Lets see it.

def showname(name="Not Supplied",age=0):
    if name=="Not Supllied":
        print "Please supply the name"
        print "your age is =%d"%age
    elif age==0:
        print "Hello %s"%(name)
        print "You did not supplied the age, common don't be ashamed of your age"
    elif name=="Not Supplied" and age==0:
        print "Please supply the name and age"
    else:
        print "Hello",name," \n Your age is only ",age

while 1:
   
    name=raw_input("Press ctrl+c to quit. \nplease enter your name :")
    age =raw_input ("please enter your age :" )
    if name=="":
        showname(age)
    elif age=="":
        showname(name)
    elif age=="" and name=="":
        showname()
    else:
        showname(name,age)
   
This program contains some logical mistakes , can you identify them? if not see my blog about loops and conditionals.

  

Friday, June 26, 2015

Writing python codes

So far all the codes I wrote was in Python Idle or terminal. Now is the time to write some code in file.
Open your favourite notepad or text editor or if you are using Python idle go to file ->new.
Write the following codes -
import math
a=9
b=math.sqrt(a)
print b



Save as ex1.py or with any other name you want with a .py extension.
For idle simply press f5 to run the program. For Linux go to the directory of the file by using cd command. And to run it type -
$python ex1.py
3
You will see 3 as output .
So what happened? Your first program worked. You called an inbuilt Python module 'math' by using import keyword of Python. I will cover more about import later but for now remember it is used to get previously made programs of Python to your current program. So the math module, as we call them , was already made by someone and added to Python for us. The math module has the function sqrt which we are using to get the root of the value a.
And then simply print the result with print b statement.

Feautured Post

Python Trivia Post: enumerate()

Python has a very useful inbuilt function, which is called enumerate(). This is needed whenever you need the numbering of a certain element...