SlideShare a Scribd company logo
THE PYTHON STD LIB BY EXAMPLE
– PART 4: DATE,TIME AND SYSTEM
RELATED MODULES
John
Saturday, December 21, 2013
DATES AND TIMES
Brief introduction
• The time module includes clock time and the
processor run-time
• The datetime module provide a higher-level
interface for date, time and combined values.
It support arithmetic,comparison, and time
zone configuration.
• The calendar module includeweeks,months,
and years.
Function time – clock time
• Function time return the number of seconds
since the start of epoch
• Function ctime show human-readable
format.
Function clock – processor clock
time
• Use it for perfomance testing, beachmarking.
• function time.clock()
>>>import time
>>>for i in range(6,1,-1):
print '%s %0.2f %0.2f' % (time.ctime(),time.time(),time.clock())
print 'sleeping', i
time.sleep(i)
Datetime module: doing time and
date parsing
• Class datetime.time: has attribute
hour,minute,second and microsecond and
tzinfo(time zone information)
• Class datetime.date: have attribute year,
month and day.
• It is easy to create current date using
function today() method.
THE FILE SYSTEM
Brief introduction
• Standard library includes a large range of
tools working with files.
• The os module provides a way regardless the
operation systems.
• The glob module help scan the directory
contents
Work with file
• open:create, open, and modify files
• remove: delete files
Code Example:
import os
fi = open(file)
fo = open(temp,”w”) #w mean write permisson
for s in fi.readlines():
fo.write(s)
fi.close
fo.close
os.remove(back)
Work with directory
• listdir,chdir,mkdir,rmdir,getcwd: Please
guess the function by the name
import os
os.getpwd() # get the current dir
os.chdir(‘..’) # change to the parent directory
os.getcwd()
os.listdir(‘.’) #list the file under the dir
os.mkdir(‘./temp1’) #make new dir
os.rmdir(‘./temp1’) #delete the dir
os.listdir(‘.’) # check if the delete is successful
Work with directory - cont
• removedirs,makedirs:
remove and create directory hierarchies.
Instead, rmdir and mkdir only handle single
directory level.
Work with file attributes
• stat: It returns a 9-tuple which contains the
size, inode change timestamp, modification
timestamp, and access privileges of a file.
Similar as unix stat.
import os
file = "samples/sample.jpg“
st = os.stat(file)
size = st[6] #file size
Working with processes
• system:runs a new command under the
current process, and waits for it to finish
import os
os.system('dir')
os.system('notepad') # open notepad
The os.path class
• This module contains functions that deal with long filenames (path
names) in various ways.
• Learn from example
import os
filename = "my/little/pony"
print "using", os.name, "..."
print "split", "=>", os.path.split(filename)
print "splitext", "=>", os.path.splitext(filename)
print "dirname", "=>", os.path.dirname(filename)
print "basename", "=>", os.path.basename(filename)
print "join", "=>", os.path.join(os.path.dirname(filename),
os.path.basename(filename))
Using the os.path module to check
what a filename represents
• Learn from example
for file in FILES:
print file, "=>",
if os.path.exists(file):
print "EXISTS",
if os.path.isabs(file):
print "ISABS",
if os.path.isdir(file):
print "ISDIR",
if os.path.isfile(file):
print "ISFILE",
if os.path.islink(file):
print "ISLINK",
if os.path.ismount(file):
print "ISMOUNT",
print
os.environ
• A mapping object representing the string
environment. => key value pairs
a = os.environ
dir(a) # show all the functions of a
a.keys() #show all the keys
a.has_key('USERNAME') #check if has this key
print a['USERNAME‘] # return the value of this key
The glob module: search dir
• An asterisk(*) mathes 0 or more characters in
a segment of a name
>>> import glob
>>> for name in glob.glob(‘dir/*’)
print name
More wildcards in glob
• A question mark (?) matches any single
character
>>> for name in glob.glob(‘./file?.txt’):
print name
./file1.txt
./file2.txt
• Others: character range e.g. [a-z], [0-9]
The tempfile module: Temporary
file system object
• Application need temporary file to store
data.
• This module create temporary files with
unique names securely.
• The file is removed automatically when it is
closed.
Use TemporaryFile create temp
file
>>> import tempfile
Another example
• Write something into temp file.
• Use seek() back to the beginning of file. Then
read it
More methods in tempfile
• Method NamedTemporaryFile()
– Similar as TemporaryFile but it give a named
temporrary file.
– Leave it to user fig out (Follow the example of
TemporaryFile).

• Method mkdtemp(): create temp dir
• Method gettempdir(): return the default dir
store temp file
Module shutil – high level file
operation
• Method copyfile(source,destination): copy
source file to destination)

• Method copy(source file, dir): copy the file
under the dir
More functions in shutil
• Method copytree(dir1, dir2): copy a dir1 to
dir2
• Method rmtree(dir): remove a dir and its
contents.
• Method move(source,destination): move a
file or dir from one place to another.
Module filecmp: compare files
and dir
• Function filecmp.cmp(file1,file2): return True
or False
• Function filecmp.dircmp(dir1,dir2).report():
output a plain-text report
THE SYS MODULE
Brief introduction
• This module provides access to some
variables used or maintained by the
interpreter and to functions that interact
strongly with the interpreter.
Working with command-line arguments
• argv list contain the arguments passed to the script.
The first is the script itself (sys.argv[0])
# File:sys-argv-example-1.py
import sys
print "script name is", sys.argv[0]
for arg in sys.argv[1:]:
print arg

• Save the code to file sys-argv-example-1.py, run
command line “python sys-argv-example-1.py –c
option1 –d option2”
Working with modules
• path: The path list contains a list of directory
names where Python looks for extension
modules

import sys
sys.path
sys.platform
• The platform variable contains the name of
the host platform
import sys
sys.platform

• Typical platform names are win32 for Windows
Working with standard input and output
• The stdin, stdout and stderr variables contain
stream objects corresponding to the standard
I/O streams.
#File “test.py”
saveout = sys.stdout
f = open(‘file1.txt’,’w’)
Sys.stdout = f #change the stdout to file1.txt
print “hello,world”
sys.stdout = saveout
In this example, “hello,world” string has written to file1.txt.
sys.exit:Exiting the program
• This function takes an optional integer value,
which is returned to the calling program.
import sys
print "hello"
sys.exit(1)
print "there"

More Related Content

What's hot (19)

Introduction to linux day-3
Introduction to linux day-3Introduction to linux day-3
Introduction to linux day-3
Gourav Varma
 
Unix command
Unix commandUnix command
Unix command
Atul Pant
 
Linux commd
Linux commdLinux commd
Linux commd
ragav03
 
Linux commd
Linux commdLinux commd
Linux commd
ragav03
 
Unix Basics For Testers
Unix Basics For TestersUnix Basics For Testers
Unix Basics For Testers
nitin lakhanpal
 
Hive data migration (export/import)
Hive data migration (export/import)Hive data migration (export/import)
Hive data migration (export/import)
Bopyo Hong
 
GPU-Accelerated Parallel Computing
GPU-Accelerated Parallel ComputingGPU-Accelerated Parallel Computing
GPU-Accelerated Parallel Computing
Jun Young Park
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQL
Mark Wong
 
Distributed Tracing, from internal SAAS insights
Distributed Tracing, from internal SAAS insightsDistributed Tracing, from internal SAAS insights
Distributed Tracing, from internal SAAS insights
Huy Do
 
Anirudh Koul. 30 Golden Rules of Deep Learning Performance
Anirudh Koul. 30 Golden Rules of Deep Learning PerformanceAnirudh Koul. 30 Golden Rules of Deep Learning Performance
Anirudh Koul. 30 Golden Rules of Deep Learning Performance
Lviv Startup Club
 
Hadoop 20111117
Hadoop 20111117Hadoop 20111117
Hadoop 20111117
exsuns
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQL
Mark Wong
 
orca_fosdem_FINAL
orca_fosdem_FINALorca_fosdem_FINAL
orca_fosdem_FINAL
addisonhuddy
 
MongoDB & Hadoop: Flexible Hourly Batch Processing Model
MongoDB & Hadoop: Flexible Hourly Batch Processing ModelMongoDB & Hadoop: Flexible Hourly Batch Processing Model
MongoDB & Hadoop: Flexible Hourly Batch Processing Model
Takahiro Inoue
 
Some Pry Features
Some Pry FeaturesSome Pry Features
Some Pry Features
Yann VERY
 
[Droid knights 2019] Tensorflow Lite 부터 ML Kit, Mobile GPU 활용 까지
[Droid knights 2019] Tensorflow Lite 부터 ML Kit, Mobile GPU 활용 까지[Droid knights 2019] Tensorflow Lite 부터 ML Kit, Mobile GPU 활용 까지
[Droid knights 2019] Tensorflow Lite 부터 ML Kit, Mobile GPU 활용 까지
Jeongah Shin
 
Linux Performance Tunning Kernel
Linux Performance Tunning KernelLinux Performance Tunning Kernel
Linux Performance Tunning Kernel
Shay Cohen
 
Linux cheat-sheet
Linux cheat-sheetLinux cheat-sheet
Linux cheat-sheet
Craig Cannon
 
File systems and inodes
File systems and inodesFile systems and inodes
File systems and inodes
Dr. Girish GS
 
Introduction to linux day-3
Introduction to linux day-3Introduction to linux day-3
Introduction to linux day-3
Gourav Varma
 
Unix command
Unix commandUnix command
Unix command
Atul Pant
 
Linux commd
Linux commdLinux commd
Linux commd
ragav03
 
Linux commd
Linux commdLinux commd
Linux commd
ragav03
 
Hive data migration (export/import)
Hive data migration (export/import)Hive data migration (export/import)
Hive data migration (export/import)
Bopyo Hong
 
GPU-Accelerated Parallel Computing
GPU-Accelerated Parallel ComputingGPU-Accelerated Parallel Computing
GPU-Accelerated Parallel Computing
Jun Young Park
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQL
Mark Wong
 
Distributed Tracing, from internal SAAS insights
Distributed Tracing, from internal SAAS insightsDistributed Tracing, from internal SAAS insights
Distributed Tracing, from internal SAAS insights
Huy Do
 
Anirudh Koul. 30 Golden Rules of Deep Learning Performance
Anirudh Koul. 30 Golden Rules of Deep Learning PerformanceAnirudh Koul. 30 Golden Rules of Deep Learning Performance
Anirudh Koul. 30 Golden Rules of Deep Learning Performance
Lviv Startup Club
 
Hadoop 20111117
Hadoop 20111117Hadoop 20111117
Hadoop 20111117
exsuns
 
pg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQLpg_proctab: Accessing System Stats in PostgreSQL
pg_proctab: Accessing System Stats in PostgreSQL
Mark Wong
 
MongoDB & Hadoop: Flexible Hourly Batch Processing Model
MongoDB & Hadoop: Flexible Hourly Batch Processing ModelMongoDB & Hadoop: Flexible Hourly Batch Processing Model
MongoDB & Hadoop: Flexible Hourly Batch Processing Model
Takahiro Inoue
 
Some Pry Features
Some Pry FeaturesSome Pry Features
Some Pry Features
Yann VERY
 
[Droid knights 2019] Tensorflow Lite 부터 ML Kit, Mobile GPU 활용 까지
[Droid knights 2019] Tensorflow Lite 부터 ML Kit, Mobile GPU 활용 까지[Droid knights 2019] Tensorflow Lite 부터 ML Kit, Mobile GPU 활용 까지
[Droid knights 2019] Tensorflow Lite 부터 ML Kit, Mobile GPU 활용 까지
Jeongah Shin
 
Linux Performance Tunning Kernel
Linux Performance Tunning KernelLinux Performance Tunning Kernel
Linux Performance Tunning Kernel
Shay Cohen
 
File systems and inodes
File systems and inodesFile systems and inodes
File systems and inodes
Dr. Girish GS
 

Viewers also liked (6)

5.Playtime
5.Playtime5.Playtime
5.Playtime
Mayank Joneja
 
Prinicples of management by irfan haider
Prinicples of management by irfan haiderPrinicples of management by irfan haider
Prinicples of management by irfan haider
Muhammad Khan
 
materi mutu layanan kebidanan
materi mutu layanan kebidananmateri mutu layanan kebidanan
materi mutu layanan kebidanan
andes septiya
 
Sorce
SorceSorce
Sorce
Argie Mabag
 
Python Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modulesPython Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modules
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsPython Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and Loops
P3 InfoTech Solutions Pvt. Ltd.
 
Prinicples of management by irfan haider
Prinicples of management by irfan haiderPrinicples of management by irfan haider
Prinicples of management by irfan haider
Muhammad Khan
 
materi mutu layanan kebidanan
materi mutu layanan kebidananmateri mutu layanan kebidanan
materi mutu layanan kebidanan
andes septiya
 
Python Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modulesPython Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modules
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsPython Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and Loops
P3 InfoTech Solutions Pvt. Ltd.
 
Ad

Similar to Python advanced 3.the python std lib by example – system related modules (20)

File and directories in python
File and directories in pythonFile and directories in python
File and directories in python
Lifna C.S
 
Module 5_Reading and Writing Files.pptx.
Module 5_Reading and Writing Files.pptx.Module 5_Reading and Writing Files.pptx.
Module 5_Reading and Writing Files.pptx.
ManjuManjunath70
 
01 file handling for class use class pptx
01 file handling for class use class pptx01 file handling for class use class pptx
01 file handling for class use class pptx
PreeTVithule1
 
Introduction to Python for Security Professionals
Introduction to Python for Security ProfessionalsIntroduction to Python for Security Professionals
Introduction to Python for Security Professionals
Andrew McNicol
 
Python Libraries and Modules
Python Libraries and ModulesPython Libraries and Modules
Python Libraries and Modules
RaginiJain21
 
pythonlibrariesandmodules-210530042906.docx
pythonlibrariesandmodules-210530042906.docxpythonlibrariesandmodules-210530042906.docx
pythonlibrariesandmodules-210530042906.docx
RameshMishra84
 
Using Python
Using PythonUsing Python
Using Python
Sebastian Grunditz
 
FILES CONCEPTS IN PYTHON PROGRAMMING.pptx
FILES CONCEPTS IN PYTHON PROGRAMMING.pptxFILES CONCEPTS IN PYTHON PROGRAMMING.pptx
FILES CONCEPTS IN PYTHON PROGRAMMING.pptx
shalinikarunakaran1
 
python file handling,exceptions are discussed
python file handling,exceptions are discussedpython file handling,exceptions are discussed
python file handling,exceptions are discussed
vidhyapm2
 
Introduction to Python_for_machine_learning.pdf
Introduction to Python_for_machine_learning.pdfIntroduction to Python_for_machine_learning.pdf
Introduction to Python_for_machine_learning.pdf
goldenflower34
 
Introduction to Python_for_machine_learning.pdf
Introduction to Python_for_machine_learning.pdfIntroduction to Python_for_machine_learning.pdf
Introduction to Python_for_machine_learning.pdf
goldenflower34
 
Python for Linux System Administration
Python for Linux System AdministrationPython for Linux System Administration
Python for Linux System Administration
vceder
 
Files in Python.pptx
Files in Python.pptxFiles in Python.pptx
Files in Python.pptx
Koteswari Kasireddy
 
Files in Python.pptx
Files in Python.pptxFiles in Python.pptx
Files in Python.pptx
Koteswari Kasireddy
 
libraries in python using different .pptx
libraries in python using different .pptxlibraries in python using different .pptx
libraries in python using different .pptx
urvashipundir04
 
packages.pptx
packages.pptxpackages.pptx
packages.pptx
SHAIKIRFAN715544
 
mod.ppt mod.ppt mod.ppt mod.ppt mod.pp d
mod.ppt mod.ppt mod.ppt mod.ppt mod.pp dmod.ppt mod.ppt mod.ppt mod.ppt mod.pp d
mod.ppt mod.ppt mod.ppt mod.ppt mod.pp d
paurushsinhad
 
jb_Modules_in_Python.ppt
jb_Modules_in_Python.pptjb_Modules_in_Python.ppt
jb_Modules_in_Python.ppt
loliktry
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
Karin Lagesen
 
python_models_import_main_init_presentation.ppt
python_models_import_main_init_presentation.pptpython_models_import_main_init_presentation.ppt
python_models_import_main_init_presentation.ppt
gouthamsaisurya555
 
File and directories in python
File and directories in pythonFile and directories in python
File and directories in python
Lifna C.S
 
Module 5_Reading and Writing Files.pptx.
Module 5_Reading and Writing Files.pptx.Module 5_Reading and Writing Files.pptx.
Module 5_Reading and Writing Files.pptx.
ManjuManjunath70
 
01 file handling for class use class pptx
01 file handling for class use class pptx01 file handling for class use class pptx
01 file handling for class use class pptx
PreeTVithule1
 
Introduction to Python for Security Professionals
Introduction to Python for Security ProfessionalsIntroduction to Python for Security Professionals
Introduction to Python for Security Professionals
Andrew McNicol
 
Python Libraries and Modules
Python Libraries and ModulesPython Libraries and Modules
Python Libraries and Modules
RaginiJain21
 
pythonlibrariesandmodules-210530042906.docx
pythonlibrariesandmodules-210530042906.docxpythonlibrariesandmodules-210530042906.docx
pythonlibrariesandmodules-210530042906.docx
RameshMishra84
 
FILES CONCEPTS IN PYTHON PROGRAMMING.pptx
FILES CONCEPTS IN PYTHON PROGRAMMING.pptxFILES CONCEPTS IN PYTHON PROGRAMMING.pptx
FILES CONCEPTS IN PYTHON PROGRAMMING.pptx
shalinikarunakaran1
 
python file handling,exceptions are discussed
python file handling,exceptions are discussedpython file handling,exceptions are discussed
python file handling,exceptions are discussed
vidhyapm2
 
Introduction to Python_for_machine_learning.pdf
Introduction to Python_for_machine_learning.pdfIntroduction to Python_for_machine_learning.pdf
Introduction to Python_for_machine_learning.pdf
goldenflower34
 
Introduction to Python_for_machine_learning.pdf
Introduction to Python_for_machine_learning.pdfIntroduction to Python_for_machine_learning.pdf
Introduction to Python_for_machine_learning.pdf
goldenflower34
 
Python for Linux System Administration
Python for Linux System AdministrationPython for Linux System Administration
Python for Linux System Administration
vceder
 
libraries in python using different .pptx
libraries in python using different .pptxlibraries in python using different .pptx
libraries in python using different .pptx
urvashipundir04
 
mod.ppt mod.ppt mod.ppt mod.ppt mod.pp d
mod.ppt mod.ppt mod.ppt mod.ppt mod.pp dmod.ppt mod.ppt mod.ppt mod.ppt mod.pp d
mod.ppt mod.ppt mod.ppt mod.ppt mod.pp d
paurushsinhad
 
jb_Modules_in_Python.ppt
jb_Modules_in_Python.pptjb_Modules_in_Python.ppt
jb_Modules_in_Python.ppt
loliktry
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
Karin Lagesen
 
python_models_import_main_init_presentation.ppt
python_models_import_main_init_presentation.pptpython_models_import_main_init_presentation.ppt
python_models_import_main_init_presentation.ppt
gouthamsaisurya555
 
Ad

More from John(Qiang) Zhang (11)

Git and github introduction
Git and github introductionGit and github introduction
Git and github introduction
John(Qiang) Zhang
 
Python testing
Python  testingPython  testing
Python testing
John(Qiang) Zhang
 
Profiling in python
Profiling in pythonProfiling in python
Profiling in python
John(Qiang) Zhang
 
Introduction to jython
Introduction to jythonIntroduction to jython
Introduction to jython
John(Qiang) Zhang
 
Introduction to cython
Introduction to cythonIntroduction to cython
Introduction to cython
John(Qiang) Zhang
 
A useful tools in windows py2exe(optional)
A useful tools in windows py2exe(optional)A useful tools in windows py2exe(optional)
A useful tools in windows py2exe(optional)
John(Qiang) Zhang
 
Python advanced 3.the python std lib by example –data structures
Python advanced 3.the python std lib by example –data structuresPython advanced 3.the python std lib by example –data structures
Python advanced 3.the python std lib by example –data structures
John(Qiang) Zhang
 
Python advanced 3.the python std lib by example – application building blocks
Python advanced 3.the python std lib by example – application building blocksPython advanced 3.the python std lib by example – application building blocks
Python advanced 3.the python std lib by example – application building blocks
John(Qiang) Zhang
 
Python advanced 2. regular expression in python
Python advanced 2. regular expression in pythonPython advanced 2. regular expression in python
Python advanced 2. regular expression in python
John(Qiang) Zhang
 
Python advanced 1.handle error, generator, decorator and decriptor
Python advanced 1.handle error, generator, decorator and decriptor Python advanced 1.handle error, generator, decorator and decriptor
Python advanced 1.handle error, generator, decorator and decriptor
John(Qiang) Zhang
 
Python advanced 3.the python std lib by example – algorithm
Python advanced 3.the python std lib by example – algorithmPython advanced 3.the python std lib by example – algorithm
Python advanced 3.the python std lib by example – algorithm
John(Qiang) Zhang
 
A useful tools in windows py2exe(optional)
A useful tools in windows py2exe(optional)A useful tools in windows py2exe(optional)
A useful tools in windows py2exe(optional)
John(Qiang) Zhang
 
Python advanced 3.the python std lib by example –data structures
Python advanced 3.the python std lib by example –data structuresPython advanced 3.the python std lib by example –data structures
Python advanced 3.the python std lib by example –data structures
John(Qiang) Zhang
 
Python advanced 3.the python std lib by example – application building blocks
Python advanced 3.the python std lib by example – application building blocksPython advanced 3.the python std lib by example – application building blocks
Python advanced 3.the python std lib by example – application building blocks
John(Qiang) Zhang
 
Python advanced 2. regular expression in python
Python advanced 2. regular expression in pythonPython advanced 2. regular expression in python
Python advanced 2. regular expression in python
John(Qiang) Zhang
 
Python advanced 1.handle error, generator, decorator and decriptor
Python advanced 1.handle error, generator, decorator and decriptor Python advanced 1.handle error, generator, decorator and decriptor
Python advanced 1.handle error, generator, decorator and decriptor
John(Qiang) Zhang
 
Python advanced 3.the python std lib by example – algorithm
Python advanced 3.the python std lib by example – algorithmPython advanced 3.the python std lib by example – algorithm
Python advanced 3.the python std lib by example – algorithm
John(Qiang) Zhang
 

Recently uploaded (20)

Data Validation and System Interoperability
Data Validation and System InteroperabilityData Validation and System Interoperability
Data Validation and System Interoperability
Safe Software
 
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
SOFTTECHHUB
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptxFIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptxFIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Alliance
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdfWar_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
biswajitbanerjee38
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Introduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUEIntroduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUE
Google Developer Group On Campus European Universities in Egypt
 
Analysis of the changes in the attitude of the news comments caused by knowin...
Analysis of the changes in the attitude of the news comments caused by knowin...Analysis of the changes in the attitude of the news comments caused by knowin...
Analysis of the changes in the attitude of the news comments caused by knowin...
Matsushita Laboratory
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptxFIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
Safe Software
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptxFIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Data Validation and System Interoperability
Data Validation and System InteroperabilityData Validation and System Interoperability
Data Validation and System Interoperability
Safe Software
 
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
SOFTTECHHUB
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptxFIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptxFIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Alliance
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdfWar_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
biswajitbanerjee38
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Analysis of the changes in the attitude of the news comments caused by knowin...
Analysis of the changes in the attitude of the news comments caused by knowin...Analysis of the changes in the attitude of the news comments caused by knowin...
Analysis of the changes in the attitude of the news comments caused by knowin...
Matsushita Laboratory
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptxFIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
Safe Software
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptxFIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 

Python advanced 3.the python std lib by example – system related modules

  • 1. THE PYTHON STD LIB BY EXAMPLE – PART 4: DATE,TIME AND SYSTEM RELATED MODULES John Saturday, December 21, 2013
  • 3. Brief introduction • The time module includes clock time and the processor run-time • The datetime module provide a higher-level interface for date, time and combined values. It support arithmetic,comparison, and time zone configuration. • The calendar module includeweeks,months, and years.
  • 4. Function time – clock time • Function time return the number of seconds since the start of epoch • Function ctime show human-readable format.
  • 5. Function clock – processor clock time • Use it for perfomance testing, beachmarking. • function time.clock() >>>import time >>>for i in range(6,1,-1): print '%s %0.2f %0.2f' % (time.ctime(),time.time(),time.clock()) print 'sleeping', i time.sleep(i)
  • 6. Datetime module: doing time and date parsing • Class datetime.time: has attribute hour,minute,second and microsecond and tzinfo(time zone information)
  • 7. • Class datetime.date: have attribute year, month and day. • It is easy to create current date using function today() method.
  • 9. Brief introduction • Standard library includes a large range of tools working with files. • The os module provides a way regardless the operation systems. • The glob module help scan the directory contents
  • 10. Work with file • open:create, open, and modify files • remove: delete files Code Example: import os fi = open(file) fo = open(temp,”w”) #w mean write permisson for s in fi.readlines(): fo.write(s) fi.close fo.close os.remove(back)
  • 11. Work with directory • listdir,chdir,mkdir,rmdir,getcwd: Please guess the function by the name import os os.getpwd() # get the current dir os.chdir(‘..’) # change to the parent directory os.getcwd() os.listdir(‘.’) #list the file under the dir os.mkdir(‘./temp1’) #make new dir os.rmdir(‘./temp1’) #delete the dir os.listdir(‘.’) # check if the delete is successful
  • 12. Work with directory - cont • removedirs,makedirs: remove and create directory hierarchies. Instead, rmdir and mkdir only handle single directory level.
  • 13. Work with file attributes • stat: It returns a 9-tuple which contains the size, inode change timestamp, modification timestamp, and access privileges of a file. Similar as unix stat. import os file = "samples/sample.jpg“ st = os.stat(file) size = st[6] #file size
  • 14. Working with processes • system:runs a new command under the current process, and waits for it to finish import os os.system('dir') os.system('notepad') # open notepad
  • 15. The os.path class • This module contains functions that deal with long filenames (path names) in various ways. • Learn from example import os filename = "my/little/pony" print "using", os.name, "..." print "split", "=>", os.path.split(filename) print "splitext", "=>", os.path.splitext(filename) print "dirname", "=>", os.path.dirname(filename) print "basename", "=>", os.path.basename(filename) print "join", "=>", os.path.join(os.path.dirname(filename), os.path.basename(filename))
  • 16. Using the os.path module to check what a filename represents • Learn from example for file in FILES: print file, "=>", if os.path.exists(file): print "EXISTS", if os.path.isabs(file): print "ISABS", if os.path.isdir(file): print "ISDIR", if os.path.isfile(file): print "ISFILE", if os.path.islink(file): print "ISLINK", if os.path.ismount(file): print "ISMOUNT", print
  • 17. os.environ • A mapping object representing the string environment. => key value pairs a = os.environ dir(a) # show all the functions of a a.keys() #show all the keys a.has_key('USERNAME') #check if has this key print a['USERNAME‘] # return the value of this key
  • 18. The glob module: search dir • An asterisk(*) mathes 0 or more characters in a segment of a name >>> import glob >>> for name in glob.glob(‘dir/*’) print name
  • 19. More wildcards in glob • A question mark (?) matches any single character >>> for name in glob.glob(‘./file?.txt’): print name ./file1.txt ./file2.txt • Others: character range e.g. [a-z], [0-9]
  • 20. The tempfile module: Temporary file system object • Application need temporary file to store data. • This module create temporary files with unique names securely. • The file is removed automatically when it is closed.
  • 21. Use TemporaryFile create temp file >>> import tempfile
  • 22. Another example • Write something into temp file. • Use seek() back to the beginning of file. Then read it
  • 23. More methods in tempfile • Method NamedTemporaryFile() – Similar as TemporaryFile but it give a named temporrary file. – Leave it to user fig out (Follow the example of TemporaryFile). • Method mkdtemp(): create temp dir • Method gettempdir(): return the default dir store temp file
  • 24. Module shutil – high level file operation • Method copyfile(source,destination): copy source file to destination) • Method copy(source file, dir): copy the file under the dir
  • 25. More functions in shutil • Method copytree(dir1, dir2): copy a dir1 to dir2 • Method rmtree(dir): remove a dir and its contents. • Method move(source,destination): move a file or dir from one place to another.
  • 26. Module filecmp: compare files and dir • Function filecmp.cmp(file1,file2): return True or False • Function filecmp.dircmp(dir1,dir2).report(): output a plain-text report
  • 28. Brief introduction • This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter.
  • 29. Working with command-line arguments • argv list contain the arguments passed to the script. The first is the script itself (sys.argv[0]) # File:sys-argv-example-1.py import sys print "script name is", sys.argv[0] for arg in sys.argv[1:]: print arg • Save the code to file sys-argv-example-1.py, run command line “python sys-argv-example-1.py –c option1 –d option2”
  • 30. Working with modules • path: The path list contains a list of directory names where Python looks for extension modules import sys sys.path
  • 31. sys.platform • The platform variable contains the name of the host platform import sys sys.platform • Typical platform names are win32 for Windows
  • 32. Working with standard input and output • The stdin, stdout and stderr variables contain stream objects corresponding to the standard I/O streams. #File “test.py” saveout = sys.stdout f = open(‘file1.txt’,’w’) Sys.stdout = f #change the stdout to file1.txt print “hello,world” sys.stdout = saveout In this example, “hello,world” string has written to file1.txt.
  • 33. sys.exit:Exiting the program • This function takes an optional integer value, which is returned to the calling program. import sys print "hello" sys.exit(1) print "there"