Sei sulla pagina 1di 36

Python

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<?>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<?>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<?>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<?>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<?>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<?>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<?>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<?>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<?>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

If you want to install qt designer 5 for pyton 3.6.3


Pip install pyqt5
And
Pip install PyQt5-tools
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<?>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

https://www.tecmint.com/install-python-in-linux/ - good for Installing


Python 3.6.4 in CentOS
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<?>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
https://www.youtube.com/watch?v=BJ_C1BySAA8 – good tutorial for
opencv with python

https://www.youtube.com/watch?v=7SrD4l2o-uk – good tutorial for qt


designer with python
pip install matplotlib C:\Users\Gopalakrishnan\Downloads\opencv_python-3.3.1+contrib-
cp36-cp36m-win_amd64.whl
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<?>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Python with mysql Database programming tutorial

Connecting MySQL Database in Python using PyMySQL


View more categories:

 Python Programming Tutorials


1- What is PyMySQL?
2- Install PyMySQL
3- Sample Database
4- Connect MySQL from Python with PyMySQL
5- Query Example
6- Insert Example
7- Update Example
8- Delete Example
9- Call Procedure
10- Call Function
1- What is PyMySQL?
In order to connect Python to a database you need a driver, which is a library used to Interact with the
database. For MySQLdatabase, you have such 3 Driver choices:

1. MySQL/connector for Python


2. MySQLdb
3. PyMySQL

Driver Discription
MySQL/Connector for
This is a library provided by the MySQL community.
Python
MySQLdb is a library that connects to MySQL from Python, it is written in C language a
MySQLdb
software.
This is a library that connects to MySQL from Python and it is a pure Python library. Py
PyMySQL
replace MySQLdb and work on CPython, PyPy and IronPython.
PyMySQL is an open source project, and you can see its source code here:

 https://github.com/PyMySQL/PyMySQL

2- Install PyMySQL
In order to install PyMySQL on Windows (or Ubuntu/Linux) you need to open the CMD window,
and run the following statement:
?
1 pip install PyMySQL
3- Sample Database
"Simplehr" is a sample database used in many tutorials on o7planning. In the post, I also use it. You
can create the database based on the guide below:

 Sample Database
4- Connect MySQL from Python with PyMySQL
The following simple example uses Python to connect to MySQL and query the Department table:
connectExample.py
?
1 import pymysql.cursors
2
3 # Connect to the database.
4 connection = pymysql.connect(host='192.168.5.134',
5 user='root',
password='1234',
6
7 db='simplehr',
8 charset='utf8mb4',
9 cursorclass=pymysql.cursor
10 s.DictCursor)
11
12 print ("connect successful!!")
13
14 try:
15
16
17 with connection.cursor() as cursor:
18
19 # SQL
20 sql = "SELECT Dept_No, Dept_Name FROM
21 Department "
22
23 # Execute query.
24 cursor.execute(sql)
25
print ("cursor.description: ",
26
cursor.description)
27
28
print()
29
30 for row in cursor:
31 print(row)
32
33 finally:
# Close connection.
connection.close()
Results of the example:

Utility Module:
The advice here is that you should create a utility module to connect to the database. In case I create a
module named as"myconnutils", which defines the getConnection() function to returns
a connection.
myconnutils.py
?
1 import pymysql.cursors
2
3 # Function return a connection.
4 def getConnection():
5
6 # You can change the connection arguments.
7 connection =
8 pymysql.connect(host='192.168.5.129',
9 user='root',
10 password='1234',
11
12 db='simplehr',
charset='utf8mb4'
13
,
cursorclass=pymys
ql.cursors.DictCursor)
return connection

5- Query Example
The following example queries the Employee table, Python uses %s as a "placeholder" for the
parameter, which is independent of the parameter type. For example:
?
sql1 = "Insert into Department (Dept_Id, Dept_No,
1
Dept_Name) values (%s, %s, %s) "
2
3 sql2 = "Select * from Employee Where Dept_Id = %s "
queryExample.py
?
1 # Use your utility module.
2 import myconnutils
3
4
5 connection = myconnutils.getConnection()
6
7 print ("Connect successful!")
8
9 sql = "Select Emp_No, Emp_Name, Hire_Date from
Employee Where Dept_Id = %s "
10
11
try :
12 cursor = connection.cursor()
13
14 # Execute sql, and pass 1 parameter.
15 cursor.execute(sql, ( 10 ) )
16
17
18
19 print ("cursor.description: ", cursor.description)
20
21 print()
22
23 for row in cursor:
24 print (" ----------- ")
25 print("Row: ", row)
26 print ("Emp_No: ", row["Emp_No"])
27 print ("Emp_Name: ", row["Emp_Name"])
28 print ("Hire_Date: ", row["Hire_Date"] ,
29 type(row["Hire_Date"]) )
30
31 finally:
# Close connection.
32
connection.close()

6- Insert Example
insertExample.py
?
1 # Use your utility module.
2 import myconnutils
3 import pymysql.cursors
4
5
6 connection = myconnutils.getConnection()
7
print ("Connect successful!")
8
9
10
11
try :
12 cursor = connection.cursor()
13
14 sql = "Select max(Grade) as Max_Grade from
15 Salary_Grade "
16 cursor.execute(sql)
17
18 # 1 row.
19 oneRow = cursor.fetchone()
20
21 # Output: {'Max_Grade': 4} or {'Max_Grade':
22 None}
23 print ("Row Result: ", oneRow)
24
25 grade = 1
26
27 if oneRow != None and oneRow["Max_Grade"] !=
28 None:
grade = oneRow["Max_Grade"] + 1
29
30
cursor = connection.cursor()
31
32
33
sql = "Insert into Salary_Grade (Grade,
34
High_Salary, Low_Salary) " \
35
+ " values (%s, %s, %s) "
36
37 print ("Insert Grade: ", grade)
38
39 # Execute sql, and pass 3 parameters.
40 cursor.execute(sql, (grade, 2000, 1000 ) )
41
42 connection.commit()
43
finally:
connection.close()

7- Update Example
updateExample.py
?
1 # Use your utility module.
2 import myconnutils
3 import pymysql.cursors
4 import datetime
5
6
7 connection = myconnutils.getConnection()
8
9 print ("Connect successful!")
10
11
12
13 try :
14 cursor = connection.cursor()
15
16 sql = "Update Employee set Salary = %s,
17 Hire_Date = %s where Emp_Id = %s "
18
19 # Hire_Date
newHireDate = datetime.date(2002, 10, 11)
20
21
# Execute sql, and pass 3 parameters.
22
rowCount = cursor.execute(sql, (850,
23 newHireDate, 7369 ) )
24
25 connection.commit()
26
27
28 print ("Updated! ", rowCount, " rows")
29
30 finally:
31 # Close connection.
connection.close()

8- Delete Example
deleteExample.py
?
1 # Use your utility module.
2 import myconnutils
3
4 connection = myconnutils.getConnection()
5
6 print ("Connect successful!")
7
8
9
10 try :
11 cursor = connection.cursor()
12
13 sql = "Delete from Salary_Grade where Grade = %s"
14
15 # Execute sql, and pass 1 parameters.
16 rowCount = cursor.execute(sql, ( 3 ) )
17
18 connection.commit()
19
20
21 print ("Deleted! ", rowCount, " rows")
22
23 finally:
# Close connection.
24
connection.close()
25

9- Call Procedure
There are some problems when you call a function or procedure in Python. I set up a situation like
this:
You have a procedure:

 Get_Employee_Info(p_Emp_Id, v_Emp_No, v_First_Name, v_Last_Name,


v_Hire_Date)

get_Employee_Info
?
1 DELIMITER $$
2
3 -- This procedure retrieves information of an employee,
4 -- Input parameter: p_Emp_ID (Integer)
5 -- There are four output parameters v_Emp_No,
6 v_First_Name, v_Last_Name, v_Hire_Date
7
8 CREATE PROCEDURE get_Employee_Info(p_Emp_ID Integer,
9 out v_Emp_No Va
10 rchar(50) ,
11 out v_First_Name Va
12 rchar(50) ,
13 Out v_Last_name Var
14 char(50) ,
15 Out v_Hire_date D
16 ate)
17 BEGIN
18 set v_Emp_No = concat( 'E' , Cast(p_Emp_Id as char(15))
);
--
set v_First_Name = 'Michael';
set v_Last_Name = 'Smith';
set v_Hire_date = curdate();
END
The procedure above has an input parameter p_Emp_Id and the four output
parameters v_Emp_No, v_First_Name, v_Last_Name,v_Hire_Date, and you call this procedure
from Python passing the value to p_Emp_Id to get 4 output values. Unfortunately, the value received
is not guaranteed to be true (as stated in the DB-API specification). Python can only retrieve values
from a SELECT clause.
DB-API specification:
?
1 def callproc(self, procname, args=()):
2 """Execute stored procedure procname with args
3
4 procname -- string, name of procedure to execute on
server
5
6
args -- Sequence of parameters to use with
7 procedure
8
9 Returns the original args.
10
11 Compatibility warning: PEP-249 specifies that any
12 modified
13 parameters must be returned. This is currently
14 impossible
15 as they are only available by storing them in a
16 server
17 variable and then retrieved by a query. Since
18 stored
19 procedures return zero or more result sets, there
is no
20
reliable way to get at OUT or INOUT parameters via
21
callproc.
22 The server variables are named @_procname_n, where
23 procname
24 is the parameter above and n is the position of the
25 parameter
26 (from zero). Once all result sets generated by the
27 procedure
28 have been fetched, you can issue a SELECT
@_procname_0, ...
query using .execute() to get any OUT or INOUT
values.

Compatibility warning: The act of calling a stored


procedure
itself creates an empty result set. This appears
after any
result sets generated by the procedure. This is
non-standard
behavior with respect to the DB-API. Be sure to use
nextset()
to advance through all result sets; otherwise you
may get
disconnected.
"""
However you can still solve the problem above, you need to wrap Get_Employee_Info procedure by
another procedure (for exampleGet_Employee_Info_Wrap), this procedure returns the values from
the SELECT clause.
get_Employee_Info_Wrap
?
DROP procedure IF EXISTS `get_Employee_Info_Wrap`;
1
2 DELIMITER $$
3
4 -- This procedure wrap Get_Employee_info
5
6 CREATE PROCEDURE
get_Employee_Info_Wrap(p_Emp_ID Integer,
7
8 out v_Emp_No
Varchar(50) ,
9
out v_First_Name
10
Varchar(50) ,
11
Out v_Last_name
12
Varchar(50) ,
13
Out v_Hire_date
14 Date)
15 BEGIN
16
17 Call get_Employee_Info( p_Emp_Id, v_Emp_No,
18 v_First_Name, v_Last_Name, v_Hire_Date);
19
20 -- SELECT
21
Select v_Emp_No, v_First_Name, v_Last_Name, v_Hire_Date;
END
Instead of calling the Get_Employee_Info procedure in Python,
call Get_Employee_Info_Wrap procedure.
callProcedureExample.py
?
1 # Use your utility module.
2 import myconnutils
3 import datetime
4
5
6 connection = myconnutils.getConnection()
7
8 print ("Connect successful!")
9
10
11
12 try :
13 cursor = connection.cursor()
14
15 # Get_Employee_Info_Wrap
16 # @p_Emp_Id Integer ,
17 # @v_Emp_No Varchar(50) OUTPUT
18 # @v_First_Name Varchar(50) OUTPUT
# @v_Last_Name Varchar(50) OUTPUT
19
# @v_Hire_Date Date OUTPUT
20 v_Emp_No = ""
21 v_First_Name= ""
22 v_Last_Name= ""
23 v_Hire_Date = None
24
25 inOutParams = ( 100, v_Emp_No, v_First_Name ,
26 v_Last_Name, v_Hire_Date )
27
28 resultArgs =
29 cursor.callproc("Get_Employee_Info_Wrap" ,
30 inOutParams )
31
32
33 print ('resultArgs:', resultArgs )
34 print ( 'inOutParams:', inOutParams )
35
36 print (' ----------------------------------- ')
37
38 for row in cursor:
39 print('Row: ', row )
40 print('Row[v_Emp_No]: ', row['v_Emp_No'] )
41 print('Row[v_First_Name]:
42 ', row['v_First_Name'] )
43 print('Row[v_Last_Name]:
44 ', row['v_Last_Name'] )
45
# datetime.date
46
47 v_Hire_Date = row['v_Hire_Date']
print('Row[v_Hire_Date]: ', v_Hire_Date )
48
49
finally:
# Close connection.
connection.close()
Run the example:

10- Call Function


To call a function in Python, you should create a query clause, and execute this query.
Here is the Get_Emp_No function, the input parameter is p_Emp_Id and
returns Emp_No (Employee Code).
Get_Emp_No
?
1 DROP function if Exists `Get_Emp_No`;
2
DELIMITER $$
3
4
CREATE Function Get_Emp_No (p_Emp_Id Integer) Returns
5
Varchar(50)
6
Begin
7
8
return concat('E', CAST(p_Emp_Id as char)) ;
9
10
END;
callFunctionExample.py
?
1
# Use your utility module.
2
import myconnutils
3 import datetime
4
5
6 connection = myconnutils.getConnection()
7
8 print ("Connect successful!")
9
10
11
12 try :
13 cursor = connection.cursor()
14
15 # Get_Employee_Info_Wrap
16 # @p_Emp_Id Integer
17 v_Emp_No = ""
18
19 inOutParams = ( 100 )
20
21 sql = "Select Get_Emp_No(%s) as Emp_No "
22
23 cursor.execute(sql, ( 100 ) )
24
25
26 print (' ----------------------------------- ')
27
28 for row in cursor:
29 print('Row: ', row )
print('Row[Emp_No]: ', row['Emp_No'] )
30
31
32
finally:
33
# Close connection.
34 connection.close()
35
Running the example:
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<?>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
MYSQL with Python
pip install pymysql

Working Example - Remote mysql connection

import datetime
#import mysql.connector
import pymysql
import pymysql.cursors

#cnx = pymysql.connect(host='198.57.215.227' user='srirama1_ramana',


db='srirama1_saranagati', password='annamalai2291')
cnx = pymysql.connect(host='198.57.215.227', port=3306, user='srirama1_ramana',
passwd='annamalai2291', db='srirama1_saranagati')
#cnx = pymysql.connect()
cursor = cnx.cursor()

query = ("select * from allnewsemail order by email_add")

cursor.execute(query)

file = open("e:\\waste\\saraemail.txt","w")

for row in cursor:


str = ''.join(row)
file.write(str+'\n')

cursor.close()
cnx.close()
file.close()

<><><><><><><><><><><><><><><><>

import pymysql

conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='', db='mysql')


cur = conn.cursor()
cur.execute("SELECT Host,User FROM user")
print(cur.description)
print()
for row in cur:
print(row)
cur.close()
conn.close()

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<?>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
SQL Server with Python
import pyodbc

con = pyodbc.connect("DRIVER={SQL
Server};server=GOPALA;database=suj;uid=sa;pwd=ramana1879;")
cur = con.cursor()
cur.execute("select * from StudentTable")

for row in cur:


print(row.stuname +", " + row.fathername +", " + row.dob +", " + row.sex)

First Install pyodbc


pip install pyodbc

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<?>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Voice Recognition
import speech_recognition as sr

# Record Audio
r = sr.Recognizer()
with sr.Microphone() as source:
print("Say something!")
audio = r.listen(source)

# Speech recognition using Google Speech Recognition


try:
# for testing purposes, we're just using the default API key
# to use another API key, use `r.recognize_google(audio,
key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
# instead of `r.recognize_google(audio)`
print("You said: " + r.recognize_google(audio))
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service;
{0}".format(e))

pip3 install SpeechRecognition

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<?>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

COPY PASTE TEXT TO CLIPBOARD USING PYTHON


Today, I came across a python library called Pyperclip that provides a
cross-platform Python module for copying and pasting text to the
clipboard.

Required Packages

Install pyperclip via pip pip install pyperclip


How to access Clipboard using Python

>> import pyperclip

>> pyperclip.copy("Hello world! This is copied to clipboard via


pyperclip")

>> # Now we can paste the text above using ctrl+v or command+v

>> pyperclip.paste()

# Using this paste method we can get the text which is present in the
Clipboard

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<?>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Reading and Writing CSV Files

What is a csv file ?


A CSV is a comma separated values file which allows data to be saved in a table structured format. All CSV files are plain
text , can contain numbers and letters only, and structure the data contained within them in a tabular, or table, form.

Sample CSV File Data

column1,column2,column3,column4
data11,data12,data13,data14
data21,data22,data23,data24
data31,data32,data33,data34
data41,data42,data43,data44

The csv module in Python implements classes to operate with CSV files. There are two ways to read a CSV file. You can
use the csv module's reader function or you can use the DictReader class.

Usig csv.reader
The csv.reader() method can be used to extract data from a file that contains CSV-formatted data. This method returns a
reader object, which can be iterated over to retrieve the lines of your CSV and the data is read as a list of strings.

example

import csv
with open('data.csv') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
print(row)

Every row is returned as an array and can be accessed as such, to print the first cells we could simply write: row[0], row[1],
row[2] etc.

import csv
with open('data.csv') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for col in reader:
print(col[0], " : ",col[1], " : ", col[2], " : ", col[3])

output

column1 : column2 : column3 : column4


data11 : data12 : data13 : data14
data21 : data22 : data23 : data24
data31 : data32 : data33 : data34
data41 : data42 : data43 : data44

Using DictReader class


Python's DictReader class basically creates a CSV object that behaves like a Python OrderedDict . It works by reading in
the first line of the CSV and using each comma separated value in this line as a dictionary key. The columns in each
subsequent row then behave like dictionary values and can be accessed with the appropriate key.

example

import csv
with open('data.csv') as csvfile:
reader = csv.DictReader(csvfile, delimiter=',')
for line in reader:
print(line["column1"], line["column2"],line["column3"],line["column4"])

output

data11 data12 data13 data14


data21 data22 data23 data24
data31 data32 data33 data34
data41 data42 data43 data44

Writing to CSV Files


The csv module also has two methods that you can use to write a CSV file. You can use the writer function or the
DictWriter class. The writer object presents two functions, namely writerow() and writerows() . The difference between
them, as you can probably tell from the names, is that the first function will only write one row, and the function
writerows() writes several rows at once.

example

import csv
data = [['column1','column2'],['data11','data12'],['data21','data22']]
csv_file = open('data1.csv', 'w')
with csv_file:
writer = csv.writer(csv_file)
writer.writerows(data)
print("Done")

Next : Threads and Threading in Pytho


<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<?>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Python XML Processing


What is XML ?
XML stands for eXtensible Markup Language . The XML standard is a
flexible way to create information formats and electronically share
structured data via the public Internet, as well as via corporate
networks.

XML Parser
The Document Object Model (DOM) defines a standard for accessing
and manipulating documents. The XML DOM defines a standard way
for accessing and manipulating XML documents. It presents an XML
document as a tree-structure.

XML parsing in Python


Python can parse xml documents in several ways. It has traditional
dom and sax parsers. This chapter will focus on using inbuilt xml
module in python for parsing XML.

Sample XML document

<data>
<items>
<item name="product1"></item>
<item name="product2"></item>
<item name="product3"></item>
<item name="product4"></item>
<item name="product5"></item>
</items>
</data>
Copy and paste the above xml code in a text file and save it as
"data.xml" in working directory.
ElementTree XML API
The xml.etree.ElementTree module implements a simple and efficient
API for parsing and creating XML data. The Element type is a flexible
container object, designed to store hierarchical data structures in
memory.

example

import xml.etree.ElementTree
doc = xml.etree.ElementTree.parse('data.xml').getroot()
for elem in doc.findall('items/item'):
print (elem.get('name'))

output

product1
product2
product3
product4
product5

Minimal DOM implementation(xml.dom.minidom)


DOM Example
The xml.dom.minidom is a minimal implementation of the Document
Object Model interface, with an API similar to that in other languages.
It is intended to be simpler than the full DOM and also significantly
smaller. Programmers who are not already proficient with the DOM
should consider using the xml.etree.ElementTree module for their
XML processing instead.

example
from xml.dom import minidom
xmldoc = minidom.parse('data.xml')
product_list = xmldoc.getElementsByTagName('item')
print("No of Items : ", len(product_list))
for product in product_list:
print(product.attributes['name'].value)

output

No of Items : 5
product1
product2
product3
product4
product5

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<?>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Python Date and Time


Python gives the developer several tools for working with date and time . The standard libraries contains the
modules such as:

datetime
time
calendar
datetime: datetime is a module which is designed with object-oriented programming to work with date
and time in Python . It defines several classes that represent date and time.

time: time is a module that only includes functions, and constants related to date and time , there are
several classes written in C/C ++ defined on this module. For example, the struct_time class.

calendar: The calendar is a module that provides functions, and several classes related to Calendar, which
support generating images of the calendar as text, html,

These modules supply classes for manipulating dates and times in both simple and complex ways.

datetime Object
Datetime objects are probably one of the most used in any application. A datetime object is an instance of
the datetime.datetime class that represents a single point in time. The datetime module includes functions
and classes for doing date and time parsing, formatting, and arithmetic. So the datetime module can be
imported like this:

import datetime

How to get current time in Python?

import datetime
print(datetime.datetime.now())

Calendar date values are represented with the date class. Instances have attributes for year, month, and day.

example

import datetime
today = datetime.datetime.now()
print("Day : ", today.day)
print("Month : ", today.month)
print("Year : ", today.year)
print("Hour : ", today.hour)
print("Minute : ", today.minute)
print("Second : ", today.second)

time object
Time values are represented with the time class. Times have attributes for hour, minute, second, and
microsecond.

Getting current time

example

import time;
ltime = time.localtime(time.time())
print ("Local current time :", ltime)

Format the current time in Python


You can format any time as per your requirement, but a simple method can do so by calling
time.strftime(format[, t]) with the current time object as the argument t. If the t argument is not provided or
None, then the time_struct object returned by time.localtime is used.

example

import time;
ltime = time.asctime( time.localtime(time.time()) )
print ("Local current time :", ltime)

calendar object
Python has a built-in function, calendar to work with date related tasks. It defines the Calendar class , which
encapsulates calculations for values such as the dates of the weeks in a given month or year.

example
import calendar
year = 2010
month = 10
print(calendar.month(year, month))

output

October 2010
Mo Tu We Th Fr Sa Su
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<?>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Python time.sleep() Method


How can I make a time delay in Python?

Python time.sleep() Method

How can I make a time delay in Python?


Python sleep() method used to suspend the execution for given of time(in seconds). We can use
python sleep function to halt the execution of the program for given time in seconds. The actual
suspension time may be less than that requested because any caught signal will terminate the
sleep() following execution of that signal's catching routine. Also, the suspension time may be
longer than requested by an arbitrary amount because of the scheduling of other activity in the
system. You can set a delay in your Python script by passing the number of seconds you want to
delay to the sleep function.

import time
time.sleep(5) #delay for 5 seconds

When you run the above example, it will end only after five seconds.

The sleep() method supports floating point numbers, meaning you can make it wait fractions of a
second too.

import time
time.sleep(1.500)

When you run the above example, the program wait for 1 second and 500 milliseconds to finish.

time.sleep(1) # sleep for 1 seconds


time.sleep(60) # sleep for 1 minute
time.sleep(3600) # sleep for 1 hour
Time delay for infinite loop
Here is another example where something is run approximately each 5 seconds.

import time
while True:
print("Thi smessage prints each 5 seconds")
time.sleep(5) # Delay for 5 seconds

The above program run an infinite loop, so you should forcefully stop the program when you
want.

Count down program with sleep


The following program is a countdown example, using sleep method to wait 1 second each
number.

import time
wait = 10
while wait > 0:
print(wait)
time.sleep(1)
wait = wait - 1

Thread and Sleep


Threads are usually contained in processes. More than one thread can exist within the same
process. These threads share the memory and the state of the process. From the following
example you can see how sleep() method work in a multi treaded program.

import time
from threading import Thread
class Main_Thread(Thread):
def run(self):
for x in range(100, 104):
print(x, " - Main Thread")
time.sleep(5)
class Service_Thread(Thread):
def run(self):
for x in range(1, 16):
print(x)
time.sleep(1)
Main_Thread().start()
Service_Thread().start()

output

100 - Main Thread


1
2
3
4
5
101 - Main Thread
6
7
8
9
10
102 - Main Thread
11
12
13
14
15
103 - Main Thread

Accuracy of time.sleep()
The time.sleep(seconds) is not real time. The time.sleep() function uses the underlying operating
system's sleep() function, sometimes it may be off in terms of milliseconds. Most PC machines
have hardware limits in the 1-10ms range, regardless of operating system. To the operating
system, time.sleep() just means a hint. It's not a good timing mechanism, but good enough for
most applications. Generally however, unless you want to sleep for a very small period, you can
generally ignore this information.

import time
sleep_start = time.time()
for cnt in range(0,10):
print(cnt)
time.sleep(1) # 1 sec delay
sleep_end = time.time()
diff = sleep_end - sleep_start
print("Looping time :",diff)

output

Looping time : 10.040287017822266

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<?>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Which is the easiest way to simulate keyboard and mouse on


Python?
I do automated testing stuff in Python. I tend to use the following:

http://www.tizmoi.net/watsup/intro.html
Edit: Link is dead, archived
version: https://web.archive.org/web/20100224025508/http://www.tizmoi.net/watsup/intro.html
http://www.mayukhbose.com/python/IEC/index.php
I do not always (almost never) simulate key presses and mouse movement. I usually use COM
to set values of windows objects and call their .click() methods.

You can send keypress signals with this:

import win32com.client

shell = win32com.client.Dispatch("WScript.Shell")
shell.SendKeys("^a") # CTRL+A may "select all" depending on which window's focused
shell.SendKeys("{DELETE}") # Delete selected text? Depends on context. :P
shell.SendKeys("{TAB}") #Press tab... to change focus or whatever
This is all in Windows. If you're in another environment, I have no clue.

Python with Selenium with Whatsapp

#https://www.github.com/iamnosa
#Let's import the Selenium package
from selenium import webdriver

#Let's use Firefox as our browser


web = webdriver.Firefox()
web.get('http://web.whatsapp.com')
input()

#Replace Mr Kelvin with the name of your friend to spam


elem = web.find_element_by_xpath('//span[contains(text(),"Mr Kelvin")]')
elem.click()
elem1 = web.find_elements_by_class_name('input')
while True:
elem1[1].send_keys('hahahahahahaha')
web.find_element_by_class_name('send-container').click()

elem = browser.find_element_by_name("q")
elem.click()
elem.clear()
elem.send_keys("Geeks for geeks ")

elem.send_keys(Keys.RETURN)

content = driver.find_element_by_css_selector('.chat.unread')
content.click()
input_form = driver.find_element_by_css_selector('.pluggable-input-placeholder')
input_form.send_keys(str(datetime.now()),Keys.RETURN)

??????????????????????????????????????????????????????????????????????????????

Selenium WebDriver “find_element_by_xpath” on


WebElement?
elements = driver.find_elements_by_xpath("//div[@class='Display']")
title = elements[1].find_elements_by_xpath(".//div[@class='Title']")

??????????????????????????????????????????????????????????????????????????????
4. Locating Elements
There are various strategies to locate elements in a page. You can use the most appropriate one
for your case. Selenium provides the following methods to locate elements in a page:

 find_element_by_id
 find_element_by_name
 find_element_by_xpath
 find_element_by_link_text
 find_element_by_partial_link_text
 find_element_by_tag_name
 find_element_by_class_name
 find_element_by_css_selector

To find multiple elements (these methods will return a list):

 find_elements_by_name
 find_elements_by_xpath
 find_elements_by_link_text
 find_elements_by_partial_link_text
 find_elements_by_tag_name
 find_elements_by_class_name
 find_elements_by_css_selector

Apart from the public methods given above, there are two private methods which might be
useful with locators in page objects. These are the two private
methods: find_element and find_elements.

Example usage:

from selenium.webdriver.common.by import By

driver.find_element(By.XPATH, '//button[text()="Some text"]')

driver.find_elements(By.XPATH, '//button')

These are the attributes available for By class:

ID = "id"

XPATH = "xpath"

LINK_TEXT = "link text"


PARTIAL_LINK_TEXT = "partial link text"

NAME = "name"

TAG_NAME = "tag name"

CLASS_NAME = "class name"

CSS_SELECTOR = "css selector"

4.1. Locating by Id
Use this when you know id attribute of an element. With this strategy, the first element with
the idattribute value matching the location will be returned. If no element has a
matching id attribute, a NoSuchElementException will be raised.

For instance, consider this page source:

<html>

<body>

<form id="loginForm">

<input name="username" type="text" />

<input name="password" type="password" />

<input name="continue" type="submit" value="Login" />

</form>

</body>

<html>

The form element can be located like this:

login_form = driver.find_element_by_id('loginForm')

4.2. Locating by Name


Use this when you know name attribute of an element. With this strategy, the first element
with the name attribute value matching the location will be returned. If no element has a
matching name attribute, a NoSuchElementException will be raised.

For instance, consider this page source:


<html>

<body>

<form id="loginForm">

<input name="username" type="text" />

<input name="password" type="password" />

<input name="continue" type="submit" value="Login" />

<input name="continue" type="button" value="Clear" />

</form>

</body>

<html>

The username & password elements can be located like this:

username = driver.find_element_by_name('username')

password = driver.find_element_by_name('password')

This will give the “Login” button as it occurs before the “Clear” button:

continue = driver.find_element_by_name('continue')

4.3. Locating by XPath


XPath is the language used for locating nodes in an XML document. As HTML can be an
implementation of XML (XHTML), Selenium users can leverage this powerful language to
target elements in their web applications. XPath extends beyond (as well as supporting) the
simple methods of locating by id or name attributes, and opens up all sorts of new possibilities
such as locating the third checkbox on the page.

One of the main reasons for using XPath is when you don’t have a suitable id or name
attribute for the element you wish to locate. You can use XPath to either locate the element in
absolute terms (not advised), or relative to an element that does have an id or name attribute.
XPath locators can also be used to specify elements via attributes other than id and name.

Absolute XPaths contain the location of all elements from the root (html) and as a result are
likely to fail with only the slightest adjustment to the application. By finding a nearby element
with an id or name attribute (ideally a parent element) you can locate your target element
based on the relationship. This is much less likely to change and can make your tests more
robust.
For instance, consider this page source:

<html>

<body>

<form id="loginForm">

<input name="username" type="text" />

<input name="password" type="password" />

<input name="continue" type="submit" value="Login" />

<input name="continue" type="button" value="Clear" />

</form>

</body>

<html>

The form elements can be located like this:

login_form = driver.find_element_by_xpath("/html/body/form[1]")

login_form = driver.find_element_by_xpath("//form[1]")

login_form = driver.find_element_by_xpath("//form[@id='loginForm']")

1. Absolute path (would break if the HTML was changed only slightly)
2. First form element in the HTML
3. The form element with attribute named id and the value loginForm

The username element can be located like this:

username = driver.find_element_by_xpath("//form[input/@name='username']")

username = driver.find_element_by_xpath("//form[@id='loginForm']/input[1]")

username = driver.find_element_by_xpath("//input[@name='username']")

1. First form element with an input child element with attribute named name and the
value username
2. First input child element of the form element with attribute named id and the
value loginForm
3. First input element with attribute named ‘name’ and the value username

The “Clear” button element can be located like this:


clear_button =
driver.find_element_by_xpath("//input[@name='continue'][@type='button']")

clear_button =
driver.find_element_by_xpath("//form[@id='loginForm']/input[4]")

1. Input with attribute named name and the value continue and attribute named type and the
value button
2. Fourth input child element of the form element with attribute named id and
value loginForm

These examples cover some basics, but in order to learn more, the following references are
recommended:

 W3Schools XPath Tutorial


 W3C XPath Recommendation
 XPath Tutorial - with interactive examples.

There are also a couple of very useful Add-ons that can assist in discovering the XPath of an
element:

 XPath Checker - suggests XPath and can be used to test XPath results.
 Firebug - XPath suggestions are just one of the many powerful features of this very useful
add-on.
 XPath Helper - for Google Chrome

4.4. Locating Hyperlinks by Link Text


Use this when you know link text used within an anchor tag. With this strategy, the first
element with the link text value matching the location will be returned. If no element has a
matching link text attribute, a NoSuchElementException will be raised.

For instance, consider this page source:

<html>

<body>

<p>Are you sure you want to do this?</p>

<a href="continue.html">Continue</a>

<a href="cancel.html">Cancel</a>

</body>

<html>
The continue.html link can be located like this:

continue_link = driver.find_element_by_link_text('Continue')

continue_link = driver.find_element_by_partial_link_text('Conti')

4.5. Locating Elements by Tag Name


Use this when you want to locate an element by tag name. With this strategy, the first element
with the given tag name will be returned. If no element has a matching tag name,
a NoSuchElementException will be raised.

For instance, consider this page source:

<html>

<body>

<h1>Welcome</h1>

<p>Site content goes here.</p>

</body>

<html>

The heading (h1) element can be located like this:

heading1 = driver.find_element_by_tag_name('h1')

4.6. Locating Elements by Class Name


Use this when you want to locate an element by class attribute name. With this strategy, the
first element with the matching class attribute name will be returned. If no element has a
matching class attribute name, a NoSuchElementException will be raised.

For instance, consider this page source:

<html>

<body>

<p class="content">Site content goes here.</p>

</body>

<html>
The “p” element can be located like this:

content = driver.find_element_by_class_name('content')

4.7. Locating Elements by CSS Selectors


Use this when you want to locate an element by CSS selector syntax. With this strategy, the
first element with the matching CSS selector will be returned. If no element has a matching
CSS selector, a NoSuchElementException will be raised.

For instance, consider this page source:

<html>

<body>

<p class="content">Site content goes here.</p>

</body>

<html>

The “p” element can be located like this:

content = driver.find_element_by_css_selector('p.content')

Sauce Labs has good documentation on CSS selectors.

?????????????????????????????????????????????????????????????

python String Array


'''
This code use string array syntax
'''
words=[]
words.append("Life")
words.append("is")
words.append("very")
words.append("easy")
words.append("with")
words.append("Python")

for word in words:


print word

wordLed=len(words)
for i in range(0,wordLed):
print words[i]

print words

Potrebbero piacerti anche