[go: up one dir, main page]

0% found this document useful (0 votes)
14 views21 pages

PYTHON UNIT 3

The document covers advanced Python programming concepts, focusing on multithreaded programming, GUI programming, and web programming. It explains the differences between processes and threads, the benefits and risks of threading, and provides examples of multithreading in Python using the threading module. Additionally, it introduces GUI programming with Tkinter, detailing how to create GUI applications and the various widgets available.

Uploaded by

nirmala.mca
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views21 pages

PYTHON UNIT 3

The document covers advanced Python programming concepts, focusing on multithreaded programming, GUI programming, and web programming. It explains the differences between processes and threads, the benefits and risks of threading, and provides examples of multithreading in Python using the threading module. Additionally, it introduces GUI programming with Tkinter, detailing how to create GUI applications and the various widgets available.

Uploaded by

nirmala.mca
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY

16CA5202 – PYTHON PROGRAMMING


(Autonomous)
UNIT – III – ADVANCED PYTHON
Internet Client Programming – Multithreaded Programming – threads and
processes-GUI programming , Advanced CGI – Web Programming

Table of Contents

THREADED AND PROCESSES .............................................................................................. 1


MULTITHREADED PROGRAMMING ................................................................................... 4
GUI PROGRAMMING .............................................................................................................. 7
ADVANCED CGI .................................................................................................................... 17
WEB PROGRAMMING .......................................................................................................... 18

THREADED AND PROCESSES

In computing, a process is an instance of a computer program that is being executed.


Any process has 3 basic components:
 An executable program.
 The associated data needed by the program (variables, work space, buffers,
etc.)
 The execution context of the program (State of process)

Processes and Threads are two basic units of execution

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.

Thread creation is much faster than process creation.


Threads are also called as light weight process

In simple words, a thread is a sequence of such instructions within a program that


can be executed independently of other code. For simplicity, you can assume that a
thread is simply a subset of a process!

A thread contains all this information in a Thread Control Block (TCB):


 Thread Identifier: Unique id (TID) is assigned to every new thread
 Stack pointer: Points to thread’s stack in the process. Stack contains the local
variables under thread’s scope.
 Program counter: a register which stores the address of the instruction
currently being executed by thread.
 Thread state: can be running, ready, waiting, start or done.
 Thread’s register set: registers assigned to thread for computations.
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – III – ADVANCED PYTHON
 Parent process Pointer: A pointer to the Process control block (PCB) of the
process that the thread lives on.

Benefits of Threading

data-space and can communicate with each other by sh aring information.

processes.

Risk Factor of Threads


 Proper co-ordination is required between threads accessing common variables
 overuse of threads can be hazardous to program’s performance and its
maintainability.

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.

Thread Life Cycle

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.

CPU Alloted Time for every thread is : 5 Mts

Name CPU Ready Running Remainin Waiting Completed


Time Time
Thread1 10 Mts Thread1 5 mts 5 Mts ----
Thread 2 4 Mts Thread2 4 Mts --- ---- Thread2
Thread 3 4 Mts Thread3 3 Mts i/o Opr

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.

During normal course of time - Ready  running  termination.

During I/O operation – ready  running waiting ready

During More execution time – ready  running  ready  termination


Ready Queue

Multithreading is defined as the ability of a processor to execute multiple threads


concurrently.
Consider the diagram below in which a process contains two active threads:
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – III – ADVANCED PYTHON

MULTITHREADED PROGRAMMING

# Python program to illustrate the concept


# of threading
# importing the threading module
import threading

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()

# wait until thread 1 is completely executed


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – III – ADVANCED PYTHON
t1.join()
# wait until thread 2 is completely executed
t2.join()

# both threads completely executed


print("Done!")

Explanation

Let us try to understand the above code:


 To import the threading module, we do:
 import threading
 To create a new thread, we create an object of Thread class. It takes following
arguments:
 target: the function to be executed by thread
 args: the arguments to be passed to the target function
In above example, we created 2 threads with different target functions:
t1 = threading.Thread(target=print_square, args=(10,))
t2 = threading.Thread(target=print_cube, args=(5,))
 To start a thread, we use start method of Thread class.
 t1.start()
 t2.start()
 Once the threads start, the current program also keeps on executing. In order
to stop execution of current program until a thread is complete, we
use join method.
 t1.join()
 t2.join()
As a result, the current program will first wait for the completion of t1 and
then t2. Once, they are finished, the remaining statements of current program
are executed.

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:

# Python program to illustrate the concept


# of threading
import threading
import os

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__":

# print ID of current process


print("ID of process running main program: {}".format(os.getpid()))

# print name of main thread


print("Main thread name: {}".format(threading.main_thread().name))

# creating threads
t1 = threading.Thread(target=task1, name='t1')
t2 = threading.Thread(target=task2, name='t2')

# starting threads
t1.start()
t2.start()

# wait until all threads finish


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – III – ADVANCED PYTHON
t1.join()
t2.join()

ID of process running main program: 7316


Main thread name: MainThread
Task 1 assigned to thread: t1
ID of process running task 1: 7316
Task 2 assigned to thread: t2
ID of process running task 2: 7316

Let us try to understand the above code:


 We use os.getpid() function to get ID of current process.
 print("ID of process running main program: {}".format(os.getpid()))
As it is clear from the output, the process ID remains same for all threads.
 We use threading.main_thread() function to get the main thread object. In
normal conditions, the main thread is the thread from which the Python
interpreter was started. name attribute of thread object is used to get the name
of thread.
 print("Main thread name: {}".format(threading.main_thread().name))
 We use the threading.current_thread() function to get the current thread
object.
 print("Task 1 assigned to thread:
{}".format(threading.current_thread().name))
The diagram given below clears the above concept:

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.

Tk provides the following widgets:


 button
 canvas
 combo-box
 frame
 level
 check-button
 entry
 level-frame
 menu
 list - box
 menu button
 message
 tk_optionMenu
 progress-bar
 radio button
 scroll bar
 separator
 tree-view

Creating a GUI program using this Tkinter is simple.

1. Import the module Tkinter


2. Create the GUI application main window. There should be only one root
widget per application and it should be created before all widgets.
3. Add one or more of the above-mentioned widgets to the GUI application.
4. The call to mainloop makes the application enter its event loop, ie it makes it
able to respond to user events, such as mouse events and keyboard events.

import tkinter # or from tkinter import *


#creates a complete window called the tk root widget.
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – III – ADVANCED PYTHON
top = tkinter.Tk()
top.title(“ My First GUI Application”)
# Code to add widgets will go here...
top.mainloop()

root = Tk()
var = StringVar()
label = Label( root, textvariable=var, relief=RAISED, bd=6, height =10, bg = "red",
width = 10, fg = "yellow")

var.set("Hey!? How are you doing?")


label.pack()
root.mainloop()

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

Top-Level Window: Tkinter.Tk()


HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – III – ADVANCED PYTHON
All main widgets are built into the top-level window object. Tkinter and Python Programming created by the Tk class in Tkinter
and is created via the normal instantiation:

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)

Presents user list of choices to mainloop()


Listbox pick from
from tkinter import *
master =Tk()
msg = Message(master, text=' The
best way to predict the future is to
Similar to a Label, but displays invent Kay')
multi-line text. Use for on msg.config(font=('times',14))
screen instructions or to make a msg.pack()
Message custom message window mainloop()
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – III – ADVANCED PYTHON
from tkinter import *
def sel():
selection = "You selected the
option " + str(var.get())
label.config(text = selection)

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

What is the CGI?


 CGI stands for Common Gateway Interface and is set of standards around the
communication between web server and server side applications.
 These standards provide the gateway through which data can pass between the
web server and CGI application.
 The CGI specification defines how web servers will make information
available to CGI applications and how CGI applications will return data to the
web server.
Programming Language Choices
 Because CGI programming and scripting don’t refer to a specific language for
coding applications for web sites, a language has to be chosen with which to
work.
 The most common languages used for CGI applications are Perl, C, C++, TCL,
Unix shells, Java, Visual Basic, and AppleScript.

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

Configure CGI script for a python program

1. Configure xampp server


a. X – cross platform
b. A – apache
c. M – MariaDB
d. P – PHP
e. P - perl
2. Options directory and add handlers
3. Write the CGI script in the correct format
4. Save the file in a different directory
5. Run the script using the URL
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – III – ADVANCED PYTHON

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

"What is an Internet client?"


Internet is a where data are exchanged, and this interchange is made up of someone
offering a service and a user of such services.
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – III – ADVANCED PYTHON

The concept "producer-consumer" means that


Servers are the producers, providing the services, and clients consume the offered
services.
For any one particular service, there is usually only one server (process, host, etc.)
and more than one consumer.

The clients using various internet protocols such as FTP, POP3 are referred as
Internet Clients

Build a CGI application which contains friends.html and friends.py

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))

You might also like