PYTHON Unit 5
PYTHON Unit 5
Syntax
Following query creates a table named EMPLOYEE in MySQL with five columns namely, FIRST_NAME,
LAST_NAME, AGE, SEX and, INCOME.
[installation]
library = %(prefix)s/lib
include = %(prefix)s/include
bin = %(prefix)s/bin
prefix = /usr/local
[debug]
pid-file = /tmp/spam.pid
show_warnings = False
log_errors = true
[server]
nworkers: 32
port: 8080
root = /www/root
signature:
configur = ConfigParser()
print (configur.read('config.ini'))
Output :
['config.ini']
Sections : ['installation', 'debug', 'server']
Installation Library : '/usr/local/lib'
Log Errors debugged ? : True
Port Server : 8080
Worker Server : 32
Code #3
configur.set('server','port','9000')
configur.set('debug','log_errors','False')
import sys
configur.write(sys.stdout)
Output :
[installation]
library = %(prefix)s/lib
include = %(prefix)s/include
bin = %(prefix)s/bin
prefix = /usr/local
[debug]
log_errors = False
show_warnings = False
[server]
port = 9000
nworkers = 32
pid-file = /tmp/spam.pid
root = /www/root
Configuration files are well suited to specify configuration data to your program. Within
each config file, values are grouped into different sections (e.g., “installation”, “debug”
and “server”).
Each section then has a specific value for various variables in that section. For the same
purpose, there are some prominent differences between a config file and using a
Python source file.
First, the syntax is much more permissive and “sloppy.”
Pass the database details like HostName, username, and the database password in the method call. The
method returns the connection object.
Example
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")
5.
6. #printing the connection object
7. print(myconn)
Output:
Example
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google", database = "mydb")
4.
5. #printing the connection object
6. print(myconn)
Output:
1. <my_cur> = conn.cursor()
Example
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google", database =
"mydb")
4.
5. #printing the connection object
6. print(myconn)
7.
8. #creating the cursor object
9. cur = myconn.cursor()
10.
11. print(cur)
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 the current program are executed.
Example:
Let us consider a simple example using a threading module.
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))
if __name__ =="__main__":
# creating thread
t1 = threading.Thread(target=print_square, args=(10,))
t2 = threading.Thread(target=print_cube, args=(10,))
# starting thread 1
t1.start()
# starting thread 2
t2.start()
Output:
Square: 100
Cube: 1000
Done!
Example
#!/usr/bin/python
import threading
import time
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
# Get lock to synchronize threads
threadLock.acquire()
print_time(self.name, self.counter, 3)
# Free lock to release next thread
threadLock.release()
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1
threadLock = threading.Lock()
threads = []
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
# Add threads to thread list
threads.append(thread1)
threads.append(thread2)
# Wait for all threads to complete
for t in threads:
t.join()
print "Exiting Main Thread"
Example code
import os
def parentchild():
n = os.fork()
if n > 0:
print("Parent process : ", os.getpid())
else:
print("Child proces : ", os.getpid())
# Driver code
parentchild()
Output
Parent process : 8023
Child process : 8024
$
The Pseudo-terminal utility module pty is defined to handle pseudo-terminal concepts. Using this we can
start another process, and also can read or write from controlling terminal using programs.
This module is highly platform oriented. We should use UNIX systems to perform these operations.
Example code
import pty, os
def process_parent_child():
(process_id, fd) = pty.fork()
print("The Process ID for the Current process is: " + str(os.getpid()))
print("The Process ID for the Child process is: " + str(process_id))
process_parent_child()
Output
The Process ID for the Current process is: 12508
The Process ID for the Child process is: 12509