0% found this document useful (0 votes)
3 views49 pages

Unit IV V Python

PYHTON

Uploaded by

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

Unit IV V Python

PYHTON

Uploaded by

b.comcasvcas
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

File handling in Python is a powerful and versatile tool that can be used to perform a wide

range of operations. However, it is important to carefully consider the advantages and


disadvantages of file handling when writing Python programs, to ensure that the code is
secure, reliable, and performs well.
Python File Handling
Python supports file handling and allows users to handle files i.e., to read and write files,
along with many other file handling options, to operate on files. The concept of file
handling has stretched over various other languages, but the implementation is either
complicated or lengthy, like other concepts of Python, this concept here is also easy and
short. Python treats files differently as text or binary and this is important. Each line of
code includes a sequence of characters, and they form a text file. Each line of a file is
terminated with a special character, called the EOL or End of Line characters
like comma {,} or newline character. It ends the current line and tells the interpreter a new
one has begun. Let’s start with the reading and writing files.
Advantages of File Handling in Python
 Versatility: File handling in Python allows you to perform a wide range of operations,
such as creating, reading, writing, appending, renaming, and deleting files.
 Flexibility: File handling in Python is highly flexible, as it allows you to work with
different file types (e.g. text files, binary files, CSV files, etc.), and to perform different
operations on files (e.g. read, write, append, etc.).
 User–friendly: Python provides a user-friendly interface for file handling, making it
easy to create, read, and manipulate files.
 Cross-platform: Python file-handling functions work across different platforms (e.g.
Windows, Mac, Linux), allowing for seamless integration and compatibility.
Disadvantages of File Handling in Python
 Error-prone: File handling operations in Python can be prone to errors, especially if
the code is not carefully written or if there are issues with the file system (e.g. file
permissions, file locks, etc.).
 Security risks: File handling in Python can also pose security risks, especially if the
program accepts user input that can be used to access or modify sensitive files on the
system.
 Complexity: File handling in Python can be complex, especially when working with
more advanced file formats or operations. Careful attention must be paid to the code to
ensure that files are handled properly and securely.
 Performance: File handling operations in Python can be slower than other
programming languages, especially when dealing with large files or performing
complex operations.
The following “[Link]” file as an example.
Hello world
GeeksforGeeks
123 456
Python File Open
Before performing any operation on the file like reading or writing, first, we have to open
that file. For this, we should use Python’s inbuilt function open() but at the time of opening,
we have to specify the mode, which represents the purpose of the opening file.
f = open(filename, mode)
Where the following mode is supported:
1. r: open an existing file for a read operation.
2. w: open an existing file for a write operation. If the file already contains some data,
then it will be overridden but if the file is not present then it creates the file as well.
3. a: open an existing file for append operation. It won’t override existing data.
4. r+: To read and write data into the file. The previous data in the file will be overridden.
5. w+: To write and read data. It will override existing data.
6. a+: To append and read data from the file. It won’t override existing data.
Working in Read mode
There is more than one way to How to read from a file in Python . Let us see how we can
read the content of a file in read mode.
Example 1: The open command will open the Python file in the read mode and the for loop
will print each line present in the file.

# a file named "geek", will be opened with the reading mode.


file = open('[Link]', 'r')
# This will print every line one by one in the file
for each in file:
print (each)

Output:
Hello world
GeeksforGeeks
123 456

Example 2: In this example, we will extract a string that contains all characters in the
Python file then we can use [Link]().

# Python code to illustrate read() mode


file = open("[Link]", "r")
print ([Link]())

Output:
Hello world
GeeksforGeeks
123 456

Example 3: In this example, we will see how we can read a file using the with statement in
Python.

# Python code to illustrate with()


with open("[Link]") as file:
data = [Link]()
print(data)

Output:
Hello world
GeeksforGeeks
123 456
Example 4: Another way to read a file is to call a certain number of characters like in the
following code the interpreter will read the first five characters of stored data and return it
as a string:
# Python code to illustrate read() mode character wise
file = open("[Link]", "r")
print ([Link](5))

Output:
Hello
Example 5: We can also split lines while reading files in Python. The split() function splits
the variable when space is encountered. You can also split using any characters as you
wish.

# Python code to illustrate split() function


with open("[Link]", "r") as file:
data = [Link]()
for line in data:
word = [Link]()
print (word)

Output:
['Hello', 'world']
['GeeksforGeeks']
['123', '456']
Creating a File using the write() Function
Just like reading a file in Python, there are a number of ways to Writing to file in Python .
Let us see how we can write the content of a file using the write() function in Python.
Working in Write Mode
Example 1: In this example, we will see how the write mode and the write() function is
used to write in a file. The close() command terminates all the resources in use and frees the
system of this particular program.

# Python code to create a file


file = open('[Link]','w')
[Link]("This is the write command")
[Link]("It allows us to write in a particular file")
[Link]()

Output:
This is the write commandIt allows us to write in a particular file
Example 2: We can also use the written statement along with the with() function.

# Python code to illustrate with() alongwith write()


with open("[Link]", "w") as f:
[Link]("Hello World!!!")

Output:
Hello World!!!
Working of Append Mode
Let us see how the append mode works.
Example: For this example, we will use the Python file created in the previous example.
# Python code to illustrate append() mode
file = open('[Link]', 'a')
[Link]("This will add this line")
[Link]()

Output:
This is the write commandIt allows us to write in a particular fileThis will add this line
There are also various other commands in Python file handling that are used to handle
various tasks:
rstrip(): This function strips each line of a file off spaces from the right-hand side.
lstrip(): This function strips each line of a file off spaces from the left-hand side.
It is designed to provide much cleaner syntax and exception handling when you are
working with code. That explains why it’s good practice to use them with a statement
where applicable. This is helpful because using this method any files opened will be closed
automatically after one is done, so auto-cleanup.
Implementing all the functions in File Handling
In this example, we will cover all the concepts that we have seen above. Other than those,
we will also see how we can delete a file using the remove() function from Python os
module.

import os
def create_file(filename):
try:
with open(filename, 'w') as f:
[Link]('Hello, world!\n')
print("File " + filename + " created successfully.")
except IOError:
print("Error: could not create file " + filename)
def read_file(filename):
try:
with open(filename, 'r') as f:
contents = [Link]()
print(contents)
except IOError:
print("Error: could not read file " + filename)
def append_file(filename, text):
try:
with open(filename, 'a') as f:
[Link](text)
print("Text appended to file " + filename + " successfully.")
except IOError:
print("Error: could not append to file " + filename)
def rename_file(filename, new_filename):
try:
[Link](filename, new_filename)
print("File " + filename + " renamed to " + new_filename + " successfully.")
except IOError:
print("Error: could not rename file " + filename)
def delete_file(filename):
try:
[Link](filename)
print("File " + filename + " deleted successfully.")
except IOError:
print("Error: could not delete file " + filename)
if __name__ == '__main__':
filename = "[Link]"
new_filename = "new_example.txt"
create_file(filename)
read_file(filename)
append_file(filename, "This is some additional text.\n")
read_file(filename)
rename_file(filename, new_filename)
read_file(new_filename)
delete_file(new_filename)

Output:
File [Link] created successfully.
Hello, world!
Text appended to file [Link] successfully.
Hello, world!
This is some additional text.
File [Link] renamed to new_example.txt successfully.
Hello, world!
This is some additional text.
File new_example.txt deleted successfully.
DIRECTORIES
Directories are a way of storing, organizing, and separating the files on a computer. The
directory that does not have a parent is called a root directory. The way to reach the file is
called the path. The path contains a combination of directory names, folder names
separated by slashes and colon and this gives the route to a file in the system.
Directory management using Python
Python contains several modules that has a number of built-in functions to manipulate and
process data. Python has also provided modules that help us to interact with the operating
system and the files. These kinds of modules can be used for directory management also.
The modules that provide the functionalities are listed below:
 os and [Link]
 filecmp
 tempfile
 shutil

os and [Link] module

The os module is used to handle files and directories in various ways. It provides provisions
to create/rename/delete directories. This allows even to know the current working directory
and change it to another. It also allows one to copy files from one directory to another. The
major methods used for directory management is explained below.
Creating new directory:
 [Link](name) method to create a new directory.
 The desired name for the new directory is passed as the parameter.
 By default it creates the new directory in the current working directory.
 If the new directory has to be created somewhere else then that path has to be specified
and the path should contain forward slashes instead of backward ones.

import os
# creates in current working directory
[Link]('new_dir')
# creates in D:\
[Link]('D:/new_dir')

Getting Current Working Directory (CWD):


 [Link]() can be used.
 It returns a string that represents the path of the current working directory.
 [Link]() can also be used but it returns a byte string that represents the current
working directory.
 Both methods do not require any parameters to be passed.

import os
print("String format :", [Link]())
print("Byte string format :", [Link]())

Output:
String format : /home/nikhil/Desktop/gfg
Byte string format : b'/home/nikhil/Desktop/gfg'
Renaming a directory:
 [Link]() method is used to rename the directory.
 The parameters passed are old_name followed by new_name.
 If a directory already exists with the new_name passed, OSError will be raised in case
of both Unix and Windows.
 If a file already exists with the new_name, in Unix no error arises, the directory will be
renamed. But in Windows the renaming won’t happen and error will be raised.
 [Link](‘old_name’,’dest_dir:/new_name’) method works similar
to [Link]() but it moves the renamed file to the specified destination
directory(dest_dir).
For example, consider there is a file named ‘[Link]’ in current working directory. Now to
just rename it :

import os
[Link]('[Link]','file1_renamed.txt')
If renaming and moving the file to some other directory is required, then the code snippet
should be:

import os
[Link]('[Link]', 'D:/file1_renamed.txt')

Changing Current Working Directory (CWD):


 Every process in the computer system will have a directory associated with it, which is
known as Current Working Directory(CWD).
 [Link]() method is used to change it.
 The parameter passed is the path/name of the desired directory to which one wish to
shift.
Form example, If we need to change the CWD to my_folder in D:/, then the following code
snippet is used.

import os
print("Current directory :", [Link]())
# Changing directory
[Link]('/home/nikhil/Desktop/')
print("Current directory :", [Link]())

Output:
Current directory : /home/nikhil/Desktop/gfg
Current directory : /home/nikhil/Desktop
Listing the files in a directory
 A directory may contain sub-directories and a number of files in it. To list
them, [Link]() method is used.
 It either takes no parameter or one parameter.
 If no parameter is passed, then the files and sub-directories of the CWD is listed.
 If files of any other directory other than the CWD is required to be listed, then that
directory’s name/path is passed as parameter.

For example: Listing the files in the CWD- GeeksforGeeks (root directory)

import os
print("The files in CWD are :",[Link]([Link]()))

Output:
The files in CWD are : [‘site folder’, ‘.directory’, ‘[Link]’, ‘poem [Link]’, ‘left bar’,
‘images’, ‘Welcome to GeeksforGeeks!\nPosts Add [Link]’, ‘[Link]’, ‘[Link]’,
‘Sorry, you can not update core for some [Link]’, ‘gfgNikhil [Link]’, ‘[Link]’,
‘gfg’, ‘[Link]’, ‘raju’, ‘images big’]
Removing a directory
 [Link]() method is used to remove/delete a directory.
 The parameter passed is the path to that directory.
 It deletes the directory if and only if it is empty, otherwise raises an OSError.

For example, Let us consider a directory K:/files. Now to remove it, one has to ensure
whether it is empty and then proceed for deleting.

import os
dir_li=[Link]('k:/files')
if len(dir_li)==0:
print("Error!! Directory not empty!!")
else:
[Link]('k:/files')

To check whether it is a directory:


 Given a directory name or Path, [Link](path) is used to validate whether the path
is a valid directory or not.
 It returns boolean values only. Returns true if the given path is a valid directory
otherwise false.

import os
# current working directory of
# GeeksforGeeks
cwd='/'
print([Link](cwd))
# Some other directory
other='K:/'
print([Link](other))

Output
True
False
To get size of the directory:
 [Link](path_name) gives the size of the directory in bytes.
 OSError is raised if, invalid path is passed as parameter.

import os
print([Link]([Link]()))

Output
4096
Getting access and modification times:
 To get the last accessed time of a directory : [Link] (path)
 To get the last modified time of the directory : [Link] (path)
 These methods return the number of seconds since the epoch. To format it, datetime
module’s strftime( ) function can be used.
Example : Getting access and modification time of GeeksforGeeks (root) directory

import os
import datetime as dt
print("Before conversion :")
# returns seconds since epoch
print("last access time :",[Link]([Link]()))
print("last modification time :",[Link]([Link]()))
print("After conversion :")
# formatting the return value
access_time=[Link]([Link]([Link]())).strftime('%Y-%m-%d %I:%M
%p')
modification_time=[Link]([Link]([Link]())).strftime('%Y-%m-%d %I:
%M %p')
print("last access time :",access_time)
print("last modification time :",modification_time)

Output
Before conversion :
last access time : 1596897099.56
last modification time : 1596897099.56
After conversion :
last access time : 2020-08-08 02:31 PM
last modification time : 2020-08-08 02:31 PM

filecmp module

This module provides various functions to perform comparison between files and
directories. To compare the directories, an object has to be created for the
class [Link] that describes which files to ignore and which files to hide from the
functions of this class. The constructor has to be invoked before calling any of the functions
of this class. The constructor can be invoked as given below:
d = filecmp . dircmp( dir_1, dir_2, ignore=[a,b,c]/None, hide=[d,e,f]/None )
Functions for comparing directories:
1. [Link]() : Compares the two directories given while invoking the constructor and
presents a summary regarding the list of files in both the directories. In case any
identical files are found, they are also listed. Common sub-directories are also printed in
the output.

import filecmp as fc
import os
dir_1 = dir_2 = [Link]()

# creating object and invoking constructor


d = [Link](dir_1, dir_2, ignore=None, hide=None)
print("comparison 1 :")
[Link]()

Output
comparison 1 :
diff / /
Common subdirectories : ['bin', 'boot', 'dev', 'etc', 'home', 'lib', 'lib64', 'media', 'mnt', 'opt',
'proc', 'run', 'sbin', 'srv', 'sys', 'tmp', 'usr', 'var']
2. d.report_partial_closure() : Prints out the comparison between the directories
passed and also the comparisons between the immediate common sub-directories.

import filecmp as fc
import os
dir_1 = dir_2 = [Link]()
# creating object and invoking constructor
d = [Link](dir_1, dir_2, ignore=None, hide=None)
print("comparison 2 :")
d.report_partial_closure()

3. d.report_full_closure() : It is same as the previous one, but does the work


recursively. It compares and displays the common sub-directories, identical
files and common funny cases (the two things do not match in type, ie., one is a directory
and another is a file.)

import filecmp as fc
import os
dir_1 = dir_2 = [Link]()
# creating object and invoking constructor
d = [Link](dir_1, dir_2, ignore=None, hide=None)
print("comparison 3 :")
d.report_full_closure()

tempfile module:

 This module is used to create temporary files and directories.


 This creates the temporary files and directories in the temp directories created by the
Operating systems.
 For windows, the temp files can be found at the following path:
profile/AppData/Local/temp
mkdtemp() :
 It is used to create a temporary directory by passing the parameters suffix, prefix and
dir.
 The suffix and prefix corresponds to the naming conventions for the created temp
directory. suffix decides how the file name should end and prefix is decides the
beginning of the name and mostly set to ‘tmp‘.
 The dir parameter specifies the path where the temporary directory should be created.
By default the dir is set to the temp directory created by the Operating systems.
 This temporary directories are readable, writable and searchable only by the creator
using the creator’s unique ID.
 The user who created the temp dir is responsible for deleting the temporary directory
upon completion of the work.
 It returns the path of the created new directory.

import tempfile as tf
f = [Link](suffix='', prefix='tmp')
print(f)

Output
/tmp/tmp0ndvk7p_
TemporaryDirectory():
 This function makes use of mkdtemp() to create a temporary directory and the same
parameters are passed here also.
 The main difference is, the object created as a result acts as a context manager.
 The user need not manually delete the created temporary file, it is cleared automatically
by the file system.
 To get the name of the newly created temp directory, [Link] can be used.
 To delete the temporary dir explicitly, cleanup( ) function can be used.

import tempfile as tf
f = [Link](suffix='', prefix='tmp')
print("Temporary file :", [Link])
[Link]()

Output
Temporary file : /tmp/tmpp3wr65fj

shutil module

This module is concerned with number of high-level operations on files and directories. It
allows copying/moving directories from a source to destination.
[Link](s, d, symlinks=False, ignore=None, copy_function=copy2,
ignore_dangling_symlinks=False):
 Recursively copies the source directory (s) to the destination directory (d) provided that
‘d’ does not already exists.
 symlinks are also known as symbolic links which denote some virtual files or reference
folders or folders that located somewhere else. It can take values like true, false or
omitted. If true, the symlinks in source are marked as symlinks in the destination also,
but the associated metadata will not be copied. If the value is false or omitted, the
contents as well as the metadata of the linked file are copied to the destination.
 For ignore, a callable that takes the directory being visited and its contents like the
return value of [Link]() since, copytree() is a recursive functions. The files to be
ignored while copying can be named using this parameter.
 The copy2 function is used as the default copy_function because it allows copying
metadata. copy(), copystat() can also be used.
[Link](path, ignore_errors=False, onerror=None):
 Deletes an entire directory. This overcomes the main disadvantage of [Link]() that it
deletes the directory only if it is empty.
 The path should be a valid directory. The symlinks to a directory won’t be accepted.
 If ignore_error is true, then the errors raised while removing the directory will be
ignored. If false or omitted is given, then the raised errors should be handled by the
ones mentioned in onerror parameter.
 onerror is a callable that takes three parameters namely function, path and excinfo. The
first is the function that raises the exception, the next is the path to be passed to the
function and the last is the exception information returned by sys.exc_info().
[Link](s,d):
 Recursively moves the source directory to the destination specified.
 The destination is not supposed to exist already, if exists based on the [Link]()
semantics, it will be overwritten.

CSV (Comma Separated Values) format is the most common import and export format for
spreadsheets and databases. It is one of the most common methods for exchanging data
between applications and popular data format used in Data Science. It is supported by a wide
range of applications. A CSV file stores tabular data in which each data field is separated by
a delimiter(comma in most cases). To represent a CSV file, it must be saved with the .csv file
extension.
Reading from CSV file
Python contains a module called csv for the handling of CSV files. The reader class from the
module is used for reading data from a CSV file. At first, the CSV file is opened using the
open() method in ‘r’ mode(specifies read mode while opening a file) which returns the file
object then it is read by using the reader() method of CSV module that returns the reader
object that iterates throughout the lines in the specified CSV document. Syntax:
[Link](csvfile, dialect='excel', **fmtparams
Note: The ‘with‘ keyword is used along with the open() method as it simplifies exception
handling and automatically closes the CSV file. Example: Consider the below CSV file –

import csv
# opening the CSV file
with open('[Link]', mode ='r')as file:
# reading the CSV file
csvFile = [Link](file)
# displaying the contents of the CSV file
for lines in csvFile:
print(lines)

Output:
[['Steve', 13, 'A'],
['John', 14, 'F'],
['Nancy', 14, 'C'],
['Ravi', 13, 'B']]
Writing to CSV file
[Link] class is used to insert data to the CSV file. This class returns a writer object which
is responsible for converting the user’s data into a delimited string. A CSV file object should
be opened with newline=” otherwise, newline characters inside the quoted fields will not be
interpreted correctly. Syntax:
[Link](csvfile, dialect='excel', **fmtparams)
[Link] class provides two methods for writing to CSV. They
are writerow() and writerows().
 writerow(): This method writes a single row at a time. Field row can be written using
this method. Syntax:
writerow(fields)
 writerows(): This method is used to write multiple rows at a time. This can be used to
write rows list. Syntax:
writerows(rows)
Example:

# Python program to demonstrate


# writing to CSV
import csv
# field names
fields = ['Name', 'Branch', 'Year', 'CGPA']
# data rows of csv file
rows = [ ['Nikhil', 'COE', '2', '9.0'],
['Sanchit', 'COE', '2', '9.1'],
['Aditya', 'IT', '2', '9.3'],
['Sagar', 'SE', '1', '9.5'],
['Prateek', 'MCE', '3', '7.8'],
['Sahil', 'EP', '2', '9.1']]
# name of csv file
filename = "university_records.csv"
# writing to csv file
with open(filename, 'w') as csvfile:
# creating a csv writer object
csvwriter = [Link](csvfile)
# writing the fields
[Link](fields)
# writing the data rows
[Link](rows)

We can also write dictionary to the CSV file. For this the CSV module provides the
[Link] class. This class returns a writer object which maps dictionaries onto output
rows. Syntax:
[Link](csvfile, fieldnames, restval=”, extrasaction=’raise’, dialect=’excel’, *args,
**kwds)
[Link] provides two methods for writing to CSV. They are:
 writeheader(): writeheader() method simply writes the first row of your csv file using
the pre-specified fieldnames. Syntax:
 writeheader()
 writerows(): writerows method simply writes all the rows but in each row, it writes
only the values(not keys). Syntax:
 writerows(mydict)
Example:

# importing the csv module


import csv
# my data rows as dictionary objects
mydict =[{'branch': 'COE', 'cgpa': '9.0', 'name': 'Nikhil', 'year': '2'},
{'branch': 'COE', 'cgpa': '9.1', 'name': 'Sanchit', 'year': '2'},
{'branch': 'IT', 'cgpa': '9.3', 'name': 'Aditya', 'year': '2'},
{'branch': 'SE', 'cgpa': '9.5', 'name': 'Sagar', 'year': '1'},
{'branch': 'MCE', 'cgpa': '7.8', 'name': 'Prateek', 'year': '3'},
{'branch': 'EP', 'cgpa': '9.1', 'name': 'Sahil', 'year': '2'}]
# field names
fields = ['name', 'branch', 'year', 'cgpa']
# name of csv file
filename = "university_records.csv"
# writing to csv file
with open(filename, 'w') as csvfile:
# creating a csv dict writer object
writer = [Link](csvfile, fieldnames = fields)
# writing headers (field names)
[Link]()
# writing data rows
[Link](mydict)
What is JSON?
JSON, short for JavaScript Object Notation, is a lightweight and text-based data exchange
format. The object in JavaScript is actually motivated by scripts but it has found applications
in many different programming languages.
The primary purpose of JSON is to transfer data between servers and web applications as an
alternative to XML. JSON data is organized as a collection of key-value pairs, where each
key is a string, and values can be strings, numbers, booleans, objects, arrays, or null. JSON
data is easy for humans and machines to read and write , and its pure and concise syntax For
that reason.
Understanding JSON
JSON is a lightweight data interchange format that is easy for both humans and machines to
read and write. JSON data is represented as key-value pairs, similar to dictionaries in Python.
Let’s explore how to work with JSON data in Python.
Reading JSON Files
Python has built-in support for JSON with its json module. Consider a JSON file named
“[Link]” that contains the following text.

To read this file, use the following code:

The [Link]() method reads the JSON data.


Writing JSON Files
To create or edit a JSON file, you can use the [Link]() method. Suppose you want to
update the age of a person in JSON data:
This code reads the JSON data, updates it, and then writes it back to the file.
Why is JSON Important?
1. Readability: JSON is well-structured and easily understood, making it the preferred
choice for representing data clearly and concisely.
2. Lightweight: JSON is a compact format that stores data efficiently and cost-
effectively, making it suitable for transmitting data over the Internet.
3. Language-Agnostic: JSON is not just JavaScript. It is widely supported in a variety of
programming languages, enabling easy data exchange between technologies.
4. Nested Data: SON allows for nested structures, enabling the representation of
complex, hierarchical data, and making it ideal for APIs, configuration files, and data
storage.
5. Human and Machine-Friendly: JSON’s balance between readability and performance
makes it a good choice for human authors and software analysts.
UNIT V
Python offers multiple options for developing GUI (Graphical User Interface). Out of all the
GUI methods, tkinter is the most commonly used method. It is a standard Python interface to
the Tk GUI toolkit shipped with Python. Python tkinter is the fastest and easiest way to create
GUI applications. Creating a GUI using tkinter is an easy task.
To create a tkinter Python app:
1. Importing the module – tkinter
2. Create the main window (container)
3. Add any number of widgets to the main window
4. Apply the event Trigger on the widgets.
Importing a tkinter is the same as importing any other module in the Python code. Note that
the name of the module in Python 2.x is ‘Tkinter’ and in Python 3.x it is ‘tkinter’.
import tkinter
There are two main methods used which the user needs to remember while creating the
Python application with GUI.
1. Tk(screenName=None, baseName=None, className=’Tk’, useTk=1): To create
a main window, tkinter offers a method ‘Tk(screenName=None, baseName=None,
className=’Tk’, useTk=1)’. To change the name of the window, you can change the
className to the desired one. The basic code used to create the main window of the
application is:
m=[Link]() where m is the name of the main window object

2. mainloop(): There is a method known by the name mainloop() is used when your
application is ready to run. mainloop() is an infinite loop used to run the application,
wait for an event to occur and process the event as long as the window is not closed.
[Link]()

import tkinter
m = [Link]()
'''
widgets are added here
'''
[Link]()

Tkinter also offers access to the geometric configuration of the widgets which can organize
the widgets in the parent windows. There are mainly three geometry manager classes class.
1. pack() method:It organizes the widgets in blocks before placing in the parent widget.
2. grid() method:It organizes the widgets in grid (table-like structure) before placing in
the parent widget.
3. place() method:It organizes the widgets by placing them on specific positions
directed by the programmer.
There are a number of widgets which you can put in your tkinter application. Some of the
major widgets are explained below:
1. Button:To add a button in your application, this widget is used. The general syntax is:
w=Button(master, option=value)

master is the parameter used to represent the parent window. There are number of options
which are used to change the format of the Buttons. Number of options can be passed as
parameters separated by commas. Some of them are listed below.
 activebackground: to set the background color when button is under the
cursor.
 activeforeground: to set the foreground color when button is under the cursor.
 bg: to set the normal background color.
 command: to call a function.
 font: to set the font on the button label.
 image: to set the image on the button.
 width: to set the width of the button.
 height: to set the height of the button.
o Python

import tkinter as tk
r = [Link]()
[Link]('Counting Seconds')
button = [Link](r, text='Stop', width=25, command=[Link])
[Link]()
[Link]()

Canvas: It is used to draw pictures and other complex layout like graphics, text and widgets.
The general syntax is:
w = Canvas(master, option=value)
master is the parameter used to represent the parent window.

There are number of options which are used to change the format of the widget. Number of
options can be passed as parameters separated by commas. Some of them are listed below.
 bd: to set the border width in pixels.
 bg: to set the normal background color.
 cursor: to set the cursor used in the canvas.
 highlightcolor: to set the color shown in the focus highlight.
 width: to set the width of the widget.
 height: to set the height of the widget.
o Python

from tkinter import *


master = Tk()
w = Canvas(master, width=40, height=60)
[Link]()
canvas_height=20
canvas_width=200
y = int(canvas_height / 2)
w.create_line(0, y, canvas_width, y )
mainloop()

CheckButton: To select any number of options by displaying a number of options to a user


as toggle buttons. The general syntax is:
w = CheckButton(master, option=value)
There are number of options which are used to change the format of this widget. Number of
options can be passed as parameters separated by commas. Some of them are listed below.
 Title: To set the title of the widget.
 activebackground: to set the background color when widget is under the
cursor.
 activeforeground: to set the foreground color when widget is under the
cursor.
 bg: to set the normal background color.
 command: to call a function.
 font: to set the font on the button label.
 image: to set the image on the widget.
o Python

from tkinter import *


master = Tk()
var1 = IntVar()
Checkbutton(master, text='male', variable=var1).grid(row=0, sticky=W)
var2 = IntVar()
Checkbutton(master, text='female', variable=var2).grid(row=1, sticky=W)
mainloop()

[Link]:It is used to input the single line text entry from the user.. For multi-line text input,
Text widget is used. The general syntax is:
w=Entry(master, option=value)
master is the parameter used to represent the parent window. There are number of options
which are used to change the format of the widget. Number of options can be passed as
parameters separated by commas. Some of them are listed below.
 bd: to set the border width in pixels.
 bg: to set the normal background color.
 cursor: to set the cursor used.
 command: to call a function.
 highlightcolor: to set the color shown in the focus highlight.
 width: to set the width of the button.
 height: to set the height of the button.
o Python

from tkinter import *


master = Tk()
Label(master, text='First Name').grid(row=0)
Label(master, text='Last Name').grid(row=1)
e1 = Entry(master)
e2 = Entry(master)
[Link](row=0, column=1)
[Link](row=1, column=1)
mainloop()

Frame: It acts as a container to hold the widgets. It is used for grouping and
organizing the widgets. The general syntax is:
w = Frame(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number of
options can be passed as parameters separated by commas. Some of them are listed below.
 highlightcolor: To set the color of the focus highlight when widget has to be
focused.
 bd: to set the border width in pixels.
 bg: to set the normal background color.
 cursor: to set the cursor used.
 width: to set the width of the widget.
 height: to set the height of the widget.
o Python

from tkinter import *

root = Tk()
frame = Frame(root)
[Link]()
bottomframe = Frame(root)
[Link]( side = BOTTOM )
redbutton = Button(frame, text = 'Red', fg ='red')
[Link]( side = LEFT)
greenbutton = Button(frame, text = 'Brown', fg='brown')
[Link]( side = LEFT )
bluebutton = Button(frame, text ='Blue', fg ='blue')
[Link]( side = LEFT )
blackbutton = Button(bottomframe, text ='Black', fg ='black')
[Link]( side = BOTTOM)
[Link]()

[Link]: It refers to the display box where you can put any text or image which can be
updated any time as per the code. The general syntax is:
w=Label(master, option=value)
master is the parameter used to represent the parent window.

There are number of options which are used to change the format of the widget. Number of
options can be passed as parameters separated by commas. Some of them are listed below.
 bg: to set the normal background color.
 bg to set the normal background color.
 command: to call a function.
 font: to set the font on the button label.
 image: to set the image on the button.
 width: to set the width of the button.
 height” to set the height of the button.
o Python

from tkinter import *


root = Tk()
w = Label(root, text='[Link]!')
[Link]()
[Link]()

Listbox: It offers a list to the user from which the user can accept any number of
options. The general syntax is:
w = Listbox(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number of
options can be passed as parameters separated by commas. Some of them are listed below.
 highlightcolor: To set the color of the focus highlight when widget has to be
focused.
 bg: to set the normal background color.
 bd: to set the border width in pixels.
 font: to set the font on the button label.
 image: to set the image on the widget.
 width: to set the width of the widget.
 height: to set the height of the widget.
o Python

from tkinter import *


top = Tk()
Lb = Listbox(top)
[Link](1, 'Python')
[Link](2, 'Java')
[Link](3, 'C++')
[Link](4, 'Any other')
[Link]()
[Link]()

[Link]: It is a part of top-down menu which stays on the window all the time. Every
menubutton has its own functionality. The general syntax is:
w = MenuButton(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number of
options can be passed as parameters separated by commas. Some of them are listed below.
 activebackground: To set the background when mouse is over the widget.
 activeforeground: To set the foreground when mouse is over the widget.
 bg: to set the normal background color.
 bd: to set the size of border around the indicator.
 cursor: To appear the cursor when the mouse over the menubutton.
 image: to set the image on the widget.
 width: to set the width of the widget.
 height: to set the height of the widget.
 highlightcolor: To set the color of the focus highlight when widget has to be
focused.

from tkinter import *


top = Tk()
mb = Menubutton ( top, text = "GfG")
[Link]()
[Link] = Menu ( mb, tearoff = 0 )
mb["menu"] = [Link]
cVar = IntVar()
aVar = IntVar()
[Link].add_checkbutton ( label ='Contact', variable = cVar )
[Link].add_checkbutton ( label = 'About', variable = aVar )
[Link]()
[Link]()

[Link]: It is used to create all kinds of menus used by the application. The general syntax is:
w = Menu(master, option=value)
master is the parameter used to represent the parent window.

There are number of options which are used to change the format of this widget. Number of
options can be passed as parameters separated by commas. Some of them are listed below.
 title: To set the title of the widget.
 activebackground: to set the background color when widget is under the
cursor.
 activeforeground: to set the foreground color when widget is under the
cursor.
 bg: to set the normal background color.
 command: to call a function.
 font: to set the font on the button label.
 image: to set the image on the widget.
o Python

from tkinter import *


root = Tk()
menu = Menu(root)
[Link](menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label='File', menu=filemenu)
filemenu.add_command(label='New')
filemenu.add_command(label='Open...')
filemenu.add_separator()
filemenu.add_command(label='Exit', command=[Link])
helpmenu = Menu(menu)
menu.add_cascade(label='Help', menu=helpmenu)
helpmenu.add_command(label='About')
mainloop()

Message: It refers to the multi-line and non-editable text. It works same as that of
Label. The general syntax is:
w = Message(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number of
options can be passed as parameters separated by commas. Some of them are listed below.
 bd: to set the border around the indicator.
 bg: to set the normal background color.
 font: to set the font on the button label.
 image: to set the image on the widget.
 width: to set the width of the widget.
 height: to set the height of the widget.
o Python

from tkinter import *


main = Tk()
ourMessage ='This is our Message'
messageVar = Message(main, text = ourMessage)
[Link](bg='lightgreen')
[Link]( )
[Link]( )

[Link]: It is used to offer multi-choice option to the user. It offers several options
to the user and the user has to choose one option. The general syntax is:
w = RadioButton(master, option=value)
There are number of options which are used to change the format of this widget. Number of
options can be passed as parameters separated by commas. Some of them are listed below.
 activebackground: to set the background color when widget is under the
cursor.
 activeforeground: to set the foreground color when widget is under the
cursor.
 bg: to set the normal background color.
 command: to call a function.
 font: to set the font on the button label.
 image: to set the image on the widget.
 width: to set the width of the label in characters.
 height: to set the height of the label in characters.
o Python

from tkinter import *


root = Tk()
v = IntVar()
Radiobutton(root, text='GfG', variable=v, value=1).pack(anchor=W)
Radiobutton(root, text='MIT', variable=v, value=2).pack(anchor=W)
mainloop()

[Link]: It is used to provide a graphical slider that allows to select any value from that
scale. The general syntax is:
w = Scale(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number of
options can be passed as parameters separated by commas. Some of them are listed below.
 cursor: To change the cursor pattern when the mouse is over the widget.
 activebackground: To set the background of the widget when mouse is over
the widget.
 bg: to set the normal background color.
 orient: Set it to HORIZONTAL or VERTICAL according to the requirement.
 from_: To set the value of one end of the scale range.
 to: To set the value of the other end of the scale range.
 image: to set the image on the widget.
 width: to set the width of the widget.
o Python

from tkinter import *


master = Tk()
w = Scale(master, from_=0, to=42)
[Link]()
w = Scale(master, from_=0, to=200, orient=HORIZONTAL)
[Link]()
mainloop()

Scrollbar: It refers to the slide controller which will be used to implement listed
widgets. The general syntax is:
w = Scrollbar(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number of
options can be passed as parameters separated by commas. Some of them are listed below.
 width: to set the width of the widget.
 activebackground: To set the background when mouse is over the widget.
 bg: to set the normal background color.
 bd: to set the size of border around the indicator.
 cursor: To appear the cursor when the mouse over the menubutton.
o Python

from tkinter import *


root = Tk()
scrollbar = Scrollbar(root)
[Link]( side = RIGHT, fill = Y )
mylist = Listbox(root, yscrollcommand = [Link] )
for line in range(100):
[Link](END, 'This is line number' + str(line))
[Link]( side = LEFT, fill = BOTH )
[Link]( command = [Link] )
mainloop()

Text: To edit a multi-line text and format the way it has to be displayed. The general
syntax is:
w =Text(master, option=value)
There are number of options which are used to change the format of the text. Number of
options can be passed as parameters separated by commas. Some of them are listed below.
 highlightcolor: To set the color of the focus highlight when widget has to be
focused.
 insertbackground: To set the background of the widget.
 bg: to set the normal background color.
 font: to set the font on the button label.
 image: to set the image on the widget.
 width: to set the width of the widget.
 height: to set the height of the widget.
o Python

from tkinter import *


root = Tk()
T = Text(root, height=2, width=30)
[Link]()
[Link](END, 'GeeksforGeeks\nBEST WEBSITE\n')
mainloop()

[Link]: This widget is directly controlled by the window manager. It don’t need any
parent window to work [Link] general syntax is:
w = TopLevel(master, option=value)
There are number of options which are used to change the format of the widget. Number of
options can be passed as parameters separated by commas. Some of them are listed below.
 bg: to set the normal background color.
 bd: to set the size of border around the indicator.
 cursor: To appear the cursor when the mouse over the menubutton.
 width: to set the width of the widget.
 height: to set the height of the widget.
o Python

from tkinter import *


root = Tk()
[Link]('GfG')
top = Toplevel()
[Link]('Python')
[Link]()

SpinBox: It is an entry of ‘Entry’ widget. Here, value can be input by selecting a


fixed value of [Link] general syntax is:
w = SpinBox(master, option=value)
There are number of options which are used to change the format of the widget. Number of
options can be passed as parameters separated by commas. Some of them are listed below.
 bg: to set the normal background color.
 bd: to set the size of border around the indicator.
 cursor: To appear the cursor when the mouse over the menubutton.
 command: To call a function.
 width: to set the width of the widget.
 activebackground: To set the background when mouse is over the widget.
 disabledbackground: To disable the background when mouse is over the
widget.
 from_: To set the value of one end of the range.
 to: To set the value of the other end of the range.

from tkinter import *


master = Tk()
w = Spinbox(master, from_ = 0, to = 10)
[Link]()
mainloop()

PannedWindowIt is a container widget which is used to handle number of panes


arranged in it. The general syntax is:
w = PannedWindow(master, option=value)
master is the parameter used to represent the parent window. There are number of options
which are used to change the format of the widget. Number of options can be passed as
parameters separated by commas. Some of them are listed below.
 bg: to set the normal background color.
 bd: to set the size of border around the indicator.
 cursor: To appear the cursor when the mouse over the menubutton.
 width: to set the width of the widget.
 height: to set the height of the widget.

from tkinter import *


m1 = PanedWindow()
[Link](fill = BOTH, expand = 1)
left = Entry(m1, bd = 5)
[Link](left)
m2 = PanedWindow(m1, orient = VERTICAL)
[Link](m2)
top = Scale( m2, orient = HORIZONTAL)
[Link](top)
mainloop()
Socket programming is a way of connecting two nodes on a network to communicate with
each other. One socket(node) listens on a particular port at an IP, while the other socket
reaches out to the other to form a connection. The server forms the listener socket while the
client reaches out to the server.
They are the real backbones behind web browsing. In simpler terms, there is a server and a
client.
Socket programming is started by importing the socket library and making a simple socket.
import socket
s = [Link](socket.AF_INET, socket.SOCK_STREAM)
Here we made a socket instance and passed it two parameters. The first parameter
is AF_INET and the second one is SOCK_STREAM. AF_INET refers to the address-
family ipv4. The SOCK_STREAM means connection-oriented TCP protocol.
Now we can connect to a server using this socket.
Connecting to a server:
Note that if any error occurs during the creation of a socket then a socket. error is thrown and
we can only connect to a server by knowing its IP. You can find the IP of the server by using
this :
$ ping [Link]
You can also find the IP using python:
import socket
ip = [Link]('[Link]')
print ip
Here is an example of a script for connecting to Google.

# An example script to connect to Google using socket


# programming in Python
import socket # for socket
import sys
try:
s = [Link](socket.AF_INET, socket.SOCK_STREAM)
print ("Socket successfully created")
except [Link] as err:
print ("socket creation failed with error %s" %(err))
# default port for socket
port = 80
try:
host_ip = [Link]('[Link]')
except [Link]:
# this means could not resolve the host
print ("there was an error resolving the host")
[Link]()
# connecting to the server
[Link]((host_ip, port))
print ("the socket has successfully connected to google")

Output :
Socket successfully created
there was an error resolving the host
Here when we will be successfully connected the output will be:
Socket successfully created
the socket has successfully connected to google
 First of all, we made a socket.
 Then we resolved google’s IP and lastly, we connected to google.
 Now we need to know how can we send some data through a socket.
 For sending data the socket library has a sendall function. This function allows you to
send data to a server to which the socket is connected and the server can also send
data to the client using this function.
A simple server-client program:
Server:
A server has a bind() method which binds it to a specific IP and port so that it can listen to
incoming requests on that IP and port. A server has a listen() method which puts the server
into listening mode. This allows the server to listen to incoming connections. And last a
server has an accept() and close() method. The accept method initiates a connection with the
client and the close method closes the connection with the client.

# first of all import the socket library


import socket
# next create a socket object
s = [Link]()
print ("Socket successfully created")
# reserve a port on your computer in our
# case it is 12345 but it can be anything
port = 12345
# Next bind to the port
# we have not typed any ip in the ip field
# instead we have inputted an empty string
# this makes the server listen to requests
# coming from other computers on the network
[Link](('', port))
print ("socket binded to %s" %(port))
# put the socket into listening mode
[Link](5)
print ("socket is listening")
# a forever loop until we interrupt it or
# an error occurs
while True:
# Establish connection with client.
c, addr = [Link]()
print ('Got connection from', addr )
# send a thank you message to the client. encoding to send byte type.
[Link]('Thank you for connecting'.encode())
# Close the connection with the client
[Link]()
# Breaking once connection closed
break

 First of all, we import socket which is necessary.


 Then we made a socket object and reserved a port on our pc.
 After that, we bound our server to the specified port. Passing an empty string means
that the server can listen to incoming connections from other computers as well. If we
would have passed [Link] then it would have listened to only those calls made
within the local computer.
 After that we put the server into listening mode.5 here means that 5 connections are
kept waiting if the server is busy and if a 6th socket tries to connect then the
connection is refused.
 At last, we make a while loop and start to accept all incoming connections and close
those connections after a thank you message to all connected sockets.
Client :
Now we need something with which a server can interact. We could telnet to the server like
this just to know that our server is working. Type these commands in the terminal:
# start the server
$ python [Link]
# keep the above terminal open
# now open another terminal and type:
$ telnet localhost 12345
If ‘telnet’ is not recognized. On windows search windows features and turn on the “telnet
client” feature.
Output :
# in the [Link] terminal you will see
# this output:
Socket successfully created
socket binded to 12345
socket is listening
Got connection from ('[Link]', 52617)
# In the telnet terminal you will get this:
Trying ::1...
Trying [Link]...
Connected to localhost.
Escape character is '^]'.
Thank you for connectingConnection closed by foreign host.
This output shows that our server is working.
Now for the client-side:

# Import socket module


import socket
# Create a socket object
s = [Link]()
# Define the port on which you want to connect
port = 12345
# connect to the server on local computer
[Link](('[Link]', port))
# receive data from the server and decoding to get the string.
print ([Link](1024).decode())
# close the connection
[Link]()

 First of all, we make a socket object.


 Then we connect to localhost on port 12345 (the port on which our server runs) and
lastly, we receive data from the server and close the connection.
 Now save this file as [Link] and run it from the terminal after starting the server
script.
# start the server:
$ python [Link]
Socket successfully created
socket binded to 12345
socket is listening
Got connection from ('[Link]', 52617)
# start the client:
$ python [Link]
Thank you for connecting
By using Python, you can send emails which can be a valuable skill for automation,
communication, and data-driven processes. In this article, we will explore how to send mail
from Gmail using Python.
How can you send Emails using Python?
Python offers a library to send emails- “SMTP” Library. “smtplib” creates a Simple Mail
Transfer Protocol (SMTP) client session object which is used to send emails to any valid
Email ID on the internet.
Prerequisites
Before starting into the main aspect, we need to make sure about some prerequisites. You
need to make sure that Python is already installed in your system. To install Python in your
system-
What is SMTP?
SMTP is a protocol that is used to send emails, and as we know Python provides the
‘smtplib’ library to interact with it. Being by importing the library and establishing a
connection with your email server. Below are the following steps to send mails:
Step 1: First of all, “smtplib” library needs to be imported.
Step 2: After that create a session, we will be using its instance SMTP to encapsulate an
SMTP connection.
s = [Link]('[Link]', 587)
Step 3: In this, you need to pass the first parameter of the server location and the second
parameter of the port to use. For Gmail, we use port number 587.
Step 4: For security reasons, now put the SMTP connection in TLS mode. TLS (Transport
Layer Security) encrypts all the SMTP commands. After that, for security and authentication,
you need to pass your Gmail account credentials in the login instance. The compiler will
show an authentication error if you enter an invalid email id or password.
Step 5: Store the message you need to send in a variable say, message. Using the sendmail()
instance, send your message. sendmail() uses three parameters: sender_email_id,
receiver_email_id and message_to_be_sent. The parameters need to be in the same
sequence.
Code Implementation:
This will send the email from your account. After you have completed your task, terminate
the SMTP session by using quit().

import smtplib
# creates SMTP session
s = [Link]('[Link]', 587)
# start TLS for security
[Link]()
# Authentication
[Link]("sender_email_id", "sender_email_id_password")
# message to be sent
message = "Message_you_need_to_send"
# sending the mail
[Link]("sender_email_id", "receiver_email_id", message)
# terminating the session
[Link]()

Send Email to Multiple Recipients using Python


If you need to send the same message to different people. You can use for loop for that. For
example, you have a list of email ids to which you need to send the same mail. To do so,
insert a “for” loop between the initialization and termination of the SMTP session. Loop will
initialize turn by turn and after sending the email, the SMTP session will be terminated.

import smtplib
# list of email_id to send the mail
li = ["xxxxx@[Link]", "yyyyy@[Link]"]
for dest in li:
s = [Link]('[Link]', 587)
[Link]()
[Link]("sender_email_id", "sender_email_id_password")
message = "Message_you_need_to_send"
[Link]("sender_email_id", dest, message)
[Link]()

The Common Gateway Interface, or CGI, is a set of standards that define how information is
exchanged between the web server and a custom script. The CGI specs are currently
maintained by the NCSA.
What is CGI?
 The Common Gateway Interface, or CGI, is a standard for external gateway programs
to interface with information servers such as HTTP servers.
 The current version is CGI/1.1 and CGI/1.2 is under progress.
Web Browsing
To understand the concept of CGI, let us see what happens when we click a hyper link to
browse a particular web page or URL.
 Your 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 either the received file or
error message.
However, it is possible to set up the HTTP server so that whenever a file in a certain directory
is requested that file is not sent back; instead it is executed as a program, and whatever that
program outputs is sent back for your browser to display. This function is called the Common
Gateway Interface or CGI and the programs are called CGI scripts. These CGI programs can
be a Python Script, PERL Script, Shell Script, C or C++ program, etc.
CGI Architecture Diagram
Web Server Support and Configuration
Before you proceed with CGI Programming, make sure that your Web Server supports CGI
and it is configured to handle CGI Programs. All the CGI Programs to be executed by the
HTTP server are kept in a pre-configured directory. This directory is called CGI Directory
and by convention it is named as /var/www/cgi-bin. By convention, CGI files have extension
as. cgi, but you can keep your files with python extension .py as well.
By default, the Linux server is configured to run only the scripts in the cgi-bin directory in
/var/www. If you want to specify any other directory to run your CGI scripts, comment the
following lines in the [Link] file −
<Directory "/var/www/cgi-bin">
AllowOverride None
Options ExecCGI
Order allow,deny
Allow from all
</Directory>
<Directory "/var/www/cgi-bin">
Options All
</Directory>
The following line should also be added for apache server to treat .py file as cgi script.
AddHandler cgi-script .py
Here, we assume that you have Web Server up and running successfully and you are able to
run any other CGI program like Perl or Shell, etc.
First CGI Program
Here is a simple link, which is linked to a CGI script called [Link]. This file is kept in
/var/www/cgi-bin directory and it has following content. Before running your CGI program,
make sure you have change mode of file using chmod 755 [Link] UNIX command to make
file executable.
print ("Content-type:text/html\r\n\r\n")
print ('<html>')
print ('<head>')
print ('<title>Hello Word - First CGI Program</title>')
print ('</head>')
print ('<body>')
print ('<h2>Hello Word! This is my first CGI program</h2>')
print ('</body>')
print ('</html>')
Note − First line in the script must be the path to Python executable. It appears as a comment
in Python program, but it is called shebang line.
In Linux, it should be #!/usr/bin/python3.
In Windows, it should be #!c:/python311/[Link].
Enter the following URL in your browser −
[Link]
Hello Word! This is my first CGI program

This [Link] script is a simple Python script, which writes its output on STDOUT file, i.e.,
screen. There is one important and extra feature available which is first line to be
printed Content-type:text/html\r\n\r\n. This line is sent back to the browser and it specifies
the content type to be displayed on the browser screen.
By now you must have understood basic concept of CGI and you can write many
complicated CGI programs using Python. This script can interact with any other external
system also to exchange information such as RDBMS.
HTTP Header
The line Content-type:text/html\r\n\r\n is part of HTTP header which is sent to the browser
to understand the content. All the HTTP header will be in the following form −
HTTP Field Name: Field Content
For Example
Content-type: text/html\r\n\r\n
There are few other important HTTP headers, which you will use frequently in your CGI
Programming.

[Link]
Header & Description
.

Content-type:
1 A MIME string defining the format of the file being returned. Example is Content-
type:text/html

Expires: Date
The date the information becomes invalid. It is used by the browser to decide when a
2
page needs to be refreshed. A valid date string is in the format 01 Jan 1998 12:00:00
GMT.

Location: URL
3 The URL that is returned instead of the URL requested. You can use this field to
redirect a request to any file.

Last-modified: Date
4
The date of last modification of the resource.

Content-length: N
5 The length, in bytes, of the data being returned. The browser uses this value to report
the estimated download time for a file.

Set-Cookie: String
6
Set the cookie passed through the string
CGI Environment Variables
All the CGI programs have access to the following environment variables. These variables
play an important role while writing any CGI program.

[Link]
Variable Name & Description
.

CONTENT_TYPE
1 The data type of the content. Used when the client is sending attached content to the
server. For example, file upload.

CONTENT_LENGTH
2
The length of the query information. It is available only for POST requests.

HTTP_COOKIE
3
Returns the set cookies in the form of key & value pair.
HTTP_USER_AGENT
4 The User-Agent request-header field contains information about the user agent
originating the request. It is name of the web browser.

PATH_INFO
5
The path for the CGI script.

QUERY_STRING
6
The URL-encoded information that is sent with GET method request.

REMOTE_ADDR
7 The IP address of the remote host making the request. This is useful logging or for
authentication.

REMOTE_HOST
8 The fully qualified name of the host making the request. If this information is not
available, then REMOTE_ADDR can be used to get IR address.

REQUEST_METHOD
9 The method used to make the request. The most common methods are GET and
POST.

SCRIPT_FILENAME
10
The full path to the CGI script.

SCRIPT_NAME
11
The name of the CGI script.

SERVER_NAME
12
The server's hostname or IP Address

SERVER_SOFTWARE
13
The name and version of the software the server is running.
Here is small CGI program to list out all the CGI variables. Click this link to see the
result Get Environment
import os
print ("Content-type: text/html\r\n\r\n");
print ("<font size=+1>Environment</font><\br>");
for param in [Link]():
print ("<b>%20s</b>: %s<\br>" % (param, [Link][param]))
GET and POST Methods
You must have come across many situations when you need to pass some information from
your browser to web server and ultimately to your CGI Program. Most frequently, browser
uses two methods two pass this information to web server. These methods are GET Method
and POST Method.
Passing Information using GET method
The GET method sends the encoded user information appended to the page request. The page
and the encoded information are separated by the ? character as follows −
[Link]
 The GET method is the default method to pass information from the browser to the
web server and it produces a long string that appears in your browser's Location:box.
 Never use GET method if you have password or other sensitive information to pass to
the server.
 The GET method has size limtation: only 1024 characters can be sent in a request
string.
 The GET method sends information using QUERY_STRING header and will be
accessible in your CGI Program through QUERY_STRING environment variable.
You can pass information by simply concatenating key and value pairs along with any URL
or you can use HTML <FORM> tags to pass information using GET method.
Simple URL Example:Get Method
Here is a simple URL, which passes two values to hello_get.py program using GET method.
/cgi-bin/hello_get.py?first_name=Malhar&last_name=Lathkar
Given below is the hello_get.py script to handle the input given by web browser. We are
going to use the cgi module, which makes it very easy to access the passed information −
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = [Link]()
# Get data from fields
first_name = [Link]('first_name')
last_name = [Link]('last_name')
print ("Content-type:text/html")
print()
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>')
This would generate the following result −
Hello Malhar Lathkar
Simple FORM Example:GET Method
This example passes two values using HTML FORM and submit button. We use same CGI
script hello_get.py to handle this input.
<form action = "/cgi-bin/hello_get.py" method = "get">
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.

First Name:
Submit
Last Name:
Passing Information Using POST Method
A generally more reliable method of passing information to a CGI program is the POST
method. This packages the information in exactly the same way as GET methods, but instead
of sending it as a text string after a ? in the URL it sends it as a separate message. This
message comes into the CGI script in the form of the standard input.
Below is same hello_get.py script which handles GET as well as POST method.
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = [Link]()
# Get data from fields
first_name = [Link]('first_name')
last_name = [Link]('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>"
Let us take again same example as above which passes two values using HTML FORM and
submit button. We use same CGI script hello_get.py to handle this input.
<form action = "/cgi-bin/hello_get.py" method = "post">
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.

First Name:
Submit
Last Name:
Passing Checkbox Data to CGI Program
Checkboxes are used when more than one option is required to be selected.
Here is example HTML code for a form with two checkboxes −
<form action = "/cgi-bin/[Link]" method = "POST" target = "_blank">
<input type = "checkbox" name = "maths" value = "on" /> Maths
<input type = "checkbox" name = "physics" value = "on" /> Physics
<input type = "submit" value = "Select Subject" />
</form>
The result of this code is the following form −

Select Subject
Maths Physics
Below is [Link] script to handle input given by web browser for checkbox button.
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = [Link]()
# Get data from fields
if [Link]('maths'):
math_flag = "ON"
else:
math_flag = "OFF"
if [Link]('physics'):
physics_flag = "ON"
else:
physics_flag = "OFF"
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Checkbox - Third CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> CheckBox Maths is : %s</h2>" % math_flag
print "<h2> CheckBox Physics is : %s</h2>" % physics_flag
print "</body>"
print "</html>"
Passing Radio Button Data to CGI Program
Radio Buttons are used when only one option is required to be selected.
Here is example HTML code for a form with two radio buttons −
<form action = "/cgi-bin/[Link]" method = "post" target = "_blank">
<input type = "radio" name = "subject" value = "maths" /> Maths
<input type = "radio" name = "subject" value = "physics" /> Physics
<input type = "submit" value = "Select Subject" />
</form>
The result of this code is the following form −

Select Subject
Maths Physics
Below is [Link] script to handle input given by web browser for radio button −
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = [Link]()
# Get data from fields
if [Link]('subject'):
subject = [Link]('subject')
else:
subject = "Not set"
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Radio - Fourth CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> Selected Subject is %s</h2>" % subject
print "</body>"
print "</html>"
Passing Text Area Data to CGI Program
TEXTAREA element is used when multiline text has to be passed to the CGI Program.
Here is example HTML code for a form with a TEXTAREA box −
<form action = "/cgi-bin/[Link]" method = "post" target = "_blank">
<textarea name = "textcontent" cols = "40" rows = "4">
Type your text here...
</textarea>
<input type = "submit" value = "Submit" />
</form>
The result of this code is the following form −

Submit

Below is [Link] script to handle input given by web browser −


# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = [Link]()
# Get data from fields
if [Link]('textcontent'):
text_content = [Link]('textcontent')
else:
text_content = "Not entered"
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>";
print "<title>Text Area - Fifth CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> Entered Text Content is %s</h2>" % text_content
print "</body>"
Passing Drop Down Box Data to CGI Program
Drop Down Box is used when we have many options available but only one or two will be
selected.
Here is example HTML code for a form with one drop down box −
<form action = "/cgi-bin/[Link]" method = "post" target = "_blank">
<select name = "dropdown">
<option value = "Maths" selected>Maths</option>
<option value = "Physics">Physics</option>
</select>
<input type = "submit" value = "Submit"/>
</form>
The result of this code is the following form −

Maths Submit

Below is [Link] script to handle input given by web browser.


# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = [Link]()
# Get data from fields
if [Link]('dropdown'):
subject = [Link]('dropdown')
else:
subject = "Not entered"
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Dropdown Box - Sixth CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> Selected Subject is %s</h2>" % subject
print "</body>"
print "</html>"
Using Cookies in CGI
HTTP protocol is a stateless protocol. For a commercial website, it is required to maintain
session information among different pages. For example, one user registration ends after
completing many pages. How to maintain user's session information across all the web
pages?
In many situations, using cookies is the most efficient method of remembering and tracking
preferences, purchases, commissions, and other information required for better visitor
experience or site statistics.
How It Works?
Your server sends some data to the visitor's browser in the form of a cookie. The browser
may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive.
Now, when the visitor arrives at another page on your site, the cookie is available for
retrieval. Once retrieved, your server knows/remembers what was stored.
Cookies are a plain text data record of 5 variable-length fields −
 Expires − The date the cookie will expire. If this is blank, the cookie will expire
when the visitor quits the browser.
 Domain − The domain name of your site.
 Path − The path to the directory or web page that sets the cookie. This may be blank
if you want to retrieve the cookie from any directory or page.
 Secure − If this field contains the word "secure", then the cookie may only be
retrieved with a secure server. If this field is blank, no such restriction exists.
 Name = Value − Cookies are set and retrieved in the form of key and value pairs.
Setting up Cookies
It is very easy to send cookies to browser. These cookies are sent along with HTTP Header
before to Content-type field. Assuming you want to set UserID and Password as cookies.
Setting the cookies is done as follows −
print "Set-Cookie:UserID = XYZ;\r\n"
print "Set-Cookie:Password = XYZ123;\r\n"
print "Set-Cookie:Expires = Tuesday, 31-Dec-2007 23:12:40 GMT;\r\n"
print "Set-Cookie:Domain = [Link];\r\n"
print "Set-Cookie:Path = /perl;\n"
print "Content-type:text/html\r\n\r\n"
...........Rest of the HTML Content....
From this example, you must have understood how to set cookies. We use Set-Cookie HTTP
header to set cookies.
It is optional to set cookies attributes like Expires, Domain, and Path. It is notable that
cookies are set before sending magic line "Content-type:text/html\r\n\r\n.
Retrieving Cookies
It is very easy to retrieve all the set cookies. Cookies are stored in CGI environment variable
HTTP_COOKIE and they will have following form −
key1 = value1;key2 = value2;key3 = value3....
Here is an example of how to retrieve cookies.
# Import modules for CGI handling
from os import environ
import cgi, cgitb
if environ.has_key('HTTP_COOKIE'):
for cookie in map(strip, split(environ['HTTP_COOKIE'], ';')):
(key, value ) = split(cookie, '=');
if key == "UserID":
user_id = value
if key == "Password":
password = value
print "User ID = %s" % user_id
print "Password = %s" % password
This produces the following result for the cookies set by above script −
User ID = XYZ
Password = XYZ123
File Upload Example
To upload a file, the HTML form must have the enctype attribute set to multipart/form-
data. The input tag with the file type creates a "Browse" button.
<html>
<body>
<form enctype = "multipart/form-data" action = "save_file.py" method = "post">
<p>File: <input type = "file" name = "filename" /></p>
<p><input type = "submit" value = "Upload" /></p>
</form>
</body>
</html>
The result of this code is the following form −
File:
Upload

Above example has been disabled intentionally to save people uploading file on our server,
but you can try above code with your server.
Here is the script save_file.py to handle file upload −
import cgi, os
import cgitb; [Link]()
form = [Link]()
# Get filename here.
fileitem = form['filename']
# Test if the file was uploaded
if [Link]:
# strip leading path from file name to avoid
# directory traversal attacks
fn = [Link]([Link])
open('/tmp/' + fn, 'wb').write([Link]())
message = 'The file "' + fn + '" was uploaded successfully'
else:
message = 'No file was uploaded'
print """\
Content-Type: text/html\n
<html>
<body>
<p>%s</p>
</body>
</html>
""" % (message,)
If you run the above script on Unix/Linux, then you need to take care of replacing file
separator as follows, otherwise on your windows machine above open() statement should
work fine.
fn = [Link]([Link]("\\", "/" ))
How To Raise a "File Download" Dialog Box?
Sometimes, it is desired that you want to give option where a user can click a link and it will
pop up a "File Download" dialogue box to the user instead of displaying actual content. This
is very easy and can be achieved through HTTP header. This HTTP header is be different
from the header mentioned in previous section.
For example, if you want make a FileName file downloadable from a given link, then its
syntax is as follows −
# HTTP Header
print "Content-Type:application/octet-stream; name = \"FileName\"\r\n";
print "Content-Disposition: attachment; filename = \"FileName\"\r\n\n";
# Actual File Content will go here.
fo = open("[Link]", "rb")
str = [Link]();
print str
# Close opend file
[Link]()

You might also like