PYTHON UNIT 3
PYTHON UNIT 3
Table of Contents
Process
A process is a self contained execution environment and it can be seen as a
program or application.
Thread
Thread can be called lightweight process. Thread requires less resources to
create and exists in the process, thread shares the process resources.
Benefits of Threading
processes.
There are two modules which support the usage of threads in Python:
thread
and
threading
Please note: The thread module has been considered as "deprecated" for quite a long
time. Users have been encouraged to use the threading module instead.
new
A new thread is created, which means it is assigned a task to perform.
Ready
Once a thread is created, it is ready for the operation and enters into the ready
queue.
Running
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – III – ADVANCED PYTHON
The thread in the ready queue is assigned to CPU for execution. It is called as
running state.
Terminated
Every thread has been assigned a CPU time duration. If the thread completes the
operation within the CPU time, it goes to terminated state. If the thread is not
completing its operation then it moves back to the ready queue for its completion
process.
Waiting
During the thread execution if there is a I/O operation t o be carried out, then the
thread moves to waiting state and after the completion of I/O operation it moves
back to the ready state.
MULTITHREADED PROGRAMMING
def print_cube(num):
"""
function to print cube of given num
"""
print("Cube: {}".format(num * num * num))
def print_square(num):
"""
function to print square of given num
"""
print("Square: {}".format(num * num))
#Main Program
# creating thread
t1 = threading.Thread(target=print_square, args=(10,))
t2 = threading.Thread(target=print_cube, args=(5,))
# starting thread 1
t1.start()
# starting thread 2
t2.start()
Explanation
Consider the diagram below for a better understanding of how above program works:
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – III – ADVANCED PYTHON
Consider the python program given below in which we print thread name and
corresponding process for each task:
def task1():
print("Task 1 assigned to thread: {}".format(threading.curren t_thread().name))
print("ID of process running task 1: {}".format(os.getpid()))
def task2():
print("Task 2 assigned to thread: {}".format(threading.current_thread().name))
print("ID of process running task 2: {}".format(os.getpid()))
if __name__ == "__main__":
# creating threads
t1 = threading.Thread(target=task1, name='t1')
t2 = threading.Thread(target=task2, name='t2')
# starting threads
t1.start()
t2.start()
GUI PROGRAMMING
Most of the programs we have done till now are text-based programming. But many
applications need GUI (Graphical User Interface).
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – III – ADVANCED PYTHON
Python provides several different options for writing GUI based programs. These are
listed below:
Tkinter: It is the easiest among all to get started with. It is Python's standard
GUI (Graphical User Interface) package. It is the most commonly used toolkit
for GUI Programming in Python.
JPython: It is the Python platform for Java that is providing Python scripts
seamless access o Java class Libraries for the local machine.
wxPython: It is open-source, cross-platform GUI toolkit written in C++. It
one of the alternatives to Tkinter, which is bundled with Python.
Using Tkinter
It is the standard GUI toolkit for Python.
root = Tk()
var = StringVar()
label = Label( root, textvariable=var, relief=RAISED, bd=6, height =10, bg = "red",
width = 10, fg = "yellow")
In GUI programming, a top-level root windowing object contains all of the little
windowing objects that will be part of the complete GUI application. These can be
text labels, buttons, list boxes, etc. These individual little GUI components are
known as widgets.
The object returned by Tkinter.Tk() is usually referred to as the root window, hence
the reason why Tkinter and Python Programming some applications use root rather
than top to indicate as such.
Tkinter.mainloop() This is normally the last piece of sequential code your p rogram
runs. When the main loop is entered, the GUI takes over execution from there.
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – III – ADVANCED PYTHON
import Tkinter
top = Tkinter.Tk()
Tk Widgets
import tkinter
top = tkinter.Tk()
quit = tkinter.Button(top,
text='Hello
Similar to a Label but provides World!',command=top.quit)
additional functionality for quit.pack()
Button mouse overs, presses, tkinter.mainloop()
from tkinter import *
def cb():
print ("variable is", var.get())
win = Tk()
var = IntVar()
c = Checkbutton(win, text="Enable
Tab",variable=var,command=
Set of boxes of which any (lambda: cb()))
number can be "checked" c.pack()
Checkbutton (similar to HTML checkbox mainloop()
import tkinter
top = tkinter.Tk()
label = tkinter.Label(top, text='Hello
World!')
Label Used to contain text or images
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – III – ADVANCED PYTHON
label.pack()
tkinter.mainloop()
from tkinter import *
master = Tk()
label = Label(master, text=' You
selected')
label.pack()
listbox = Listbox(master)
listbox.pack()
listbox.insert(END, "a list entry")
for item in ["one", "two", "three",
"four"]:
listbox.insert(END, item)
index = listbox.curselection()
label = listbox.get(1)
root = Tk()
var = IntVar()
R1 = Radiobutton(root, text="Option
1", variable=var, value=1,
command=sel)
R1.pack( anchor = W )
R2 = Radiobutton(root, text="Option
2", variable=var, value=2,
command=sel)
R2.pack( anchor = W )
R3 = Radiobutton(root, text="Option
3", variable=var, value=3,
command=sel)
R3.pack( anchor = W)
Set of buttons of which only label = Label(root)
one can be "pressed" (similar to label.pack()
Radiobutton HTML radio input) root.mainloop()
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – III – ADVANCED PYTHON
from tkinter import *
master = Tk()
w = Scale(master, from_=0, to=42)
w.pack()
w = Scale(master, from_=0, to=200,
Linear "slider" widget orient=HORIZONTAL)
providing an exact value at w.pack()
Scale current setting; with defined mainloop()
Provides ability to draw shapes
(lines, ovals, polygons,
Canvas rectangles); can contain
Single-line text field with
which to collect keyboard input
Entry (similar to HTML text
Pure container for other
Frame widgets
Actual list of choices "hanging"
from a Menubutton that the
Menu user can choose
Provides scrolling functionality
to supporting widgets, i.e.,
Scrollbar Text, Canvas, Listbox,
Multi-line text field with which
to collect (or display) text from
Text user (similar to
Similar to a Frame, but
provides a separate window
Toplevel container
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – III – ADVANCED PYTHON
GUI Programming
Introducing Tkinter uses the term ‘root window” To create a new root window:
Root Window for a graphical window which from tkinter import *
accommodates all the widgets. The root = Tk(className="My first GUI") #
first step in Tkinter GUI designing is creates root window
to create a root window. # all components of thw window will
come here
root.mainloop() # To keep GUI window
running
Adding Widget refers to components that we This includes components like buttons,
Widgets add to the root window label, text area, menu, check button, entry,
canvas, sliders and other elements that are
The syntax for adding a widget is : added to the root window.
Widget-name (configuration options from tkinter import *
for the widget) root = Tk(className ="My first GUI")
#add a root window named Myfirst GUI
foo = Label(root,text="Hello World") #
add a label to root window
foo.pack()
root.mainloop()
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – III – ADVANCED PYTHON
Introducing For example clicking on the button from tkinter import Button
& Handling should result in some event. def act(): # defines an event function -
Events for click of button
print ("I-M-pressed")
foo = Button(None,text="Press
Me",command=act) # create &
configure widget 'button"
foo.pack() # defines placement &
geometry of the widget (will use it later)
foo.mainloop() # an event loop to invoke
custom function "act"
Working with A simple function is defined which from tkinter import *
TextField will print the data entered by the root = Tk(className ="My first GUI")
(Entry user in the text area, upon clicking svalue = StringVar() # defines the
Widget) of a button. widget state as string
l = Label(root,text = "Enter message in
Text Box ")
l.pack()
w = Entry(root,textvariable=svalue) #
adds a textarea widget
w.pack()
def act():
print( "you entered")
print ('%s' % svalue.get())
foo = Button(root,text="Press Me",
command=act)
foo.pack()
root.mainloop()
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – III – ADVANCED PYTHON
ADVANCED CGI
1. The Web surfer fills out a form and clicks, “Submit.” The information in the form
is sent over the Internet to the Web server.
2. The Web server “grabs” the information from the form and passes it to the CGI
software.
3. The CGI software performs whatever validation of this information that is required.
For instance, it might check to see if an e-mail address is valid. If this is a database
program, the CGI software prepares a database statement to either add, edit, or delete
information from the database.
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – III – ADVANCED PYTHON
4. The CGI software then executes the prepared database statement, which is passed
to the database driver.
5. The database driver acts as a middleman and performs the req uested action on the
database itself.
6. The results of the database action are then passed back to the database driver.
7. The database driver sends the information from the database to the CGI software.
8. The CGI software takes the information from the database and manipulates it into
the format that is desired.
9. If any static HTML pages need to be created, the CGI program accesses the Web
server computer’s file system and reads, writes, and/or edits files.
10. The CGI software then sends the result it wants the Web surfer’s browser to see
back to the Web server.
11. The Web server sends the result it got from the CGI software back to the Web
surfer’s browser.
Web Browsing
The browser contacts the HTTP web server and demands for the URL, i.e.,
filename.
Web Server parses the URL and looks for the filename. If it finds that file
then sends it back to the browser, otherwise sends an error message
indicating that you requested a wrong file.
Web browser takes response from web server and displays eith er the received
file or error message.
WEB PROGRAMMING
CGI Example
cgi.html
This example passes two values using HTML FORM and submit button. We use
same CGI script form.py to handle this input.
<form action = "/CGI-BIN/form.py" method = "postt">
First Name: <input type = "text" name = "first_name"> <br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
Here is the actual output of the above form, you enter First and Last Name and then
click submit button to see the result.
rams
First Name:
leela Submit
Last Name:
Form.py
#!/usr/bin/python
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
first_name = form.getvalue('first_name')
last_name = form.getvalue('last_name')
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Hello - Second CGI Program</title>"
print "</head>"
print "<body>"
print "<h2>Hello %s %s</h2>" % (first_name, last_name)
print "</body>"
print "</html>"
Output
The clients using various internet protocols such as FTP, POP3 are referred as
Internet Clients
This HTML file presents a form to the user with an empty field for the user's name
and a set of radio buttons for the user to choose from.
<HTML><HEAD><TITLE>
Friends CGI Demo (static screen)
</TITLE></HEAD>
<BODY><H3>Friends list for: <I>NEW USER</I></H3>
<FORM ACTION="/cgi-bin/friends1.py">
<B>Enter your Name:</B>
<INPUT TYPE=text NAME=person VALUE="NEW USER" SIZE=15>
<P><B>How many friends do you have?</B>
<INPUT TYPE=radio NAME=howmany VALUE="0" CHECKED> 0
<INPUT TYPE=radio NAME=howmany VALUE="10"> 10
<INPUT TYPE=radio NAME=howmany VALUE="25"> 25
<INPUT TYPE=radio NAME=howmany VALUE="50"> 50
<INPUT TYPE=radio NAME=howmany VALUE="100"> 100
<P><INPUT TYPE=submit></FORM></BODY></HTML>
This CGI script grabs the person and howmany fields from the form and uses that
data to create the dynamically generated results screen.
#!/usr/bin/env python
import cgi
reshtml = '''Content-Type: text/html\n
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – III – ADVANCED PYTHON
<HTML><HEAD><TITLE>
Friends CGI Demo (dynamic screen)
</TITLE></HEAD>
<BODY><H3>Friends list for: <I>%s</I></H3>
Your name is: <B>%s</B><P>
You have <B>%s</B> friends.
</BODY></HTML>'''
form = cgi.FieldStorage()
who = form['person'].value
howmany = form['howmany'].value
print (reshtml % (who, who, howmany))