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

33
THE PYTHON STD LIB BY EXAMPLE – PART 4: DATE,TIME AND SYSTEM RELATED MODULES John Sunday, May 8, 2022

Upload: john-zhang

Post on 29-Nov-2014

224 views

Category:

Technology


4 download

DESCRIPTION

 

TRANSCRIPT

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

THE PYTHON STD LIB BY EXAMPLE – PART 4: DATE,TIME AND SYSTEM

RELATED MODULES

JohnSunday, April 9, 2023

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

DATES AND TIMES

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

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.

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

Function time – clock time

• Function time return the number of seconds since the start of epoch

• Function ctime show human-readable format.

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

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)

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

Datetime module: doing time and date parsing• Class datetime.time: has attribute

hour,minute,second and microsecond and tzinfo(time zone information)

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

• Class datetime.date: have attribute year, month and day.

• It is easy to create current date using function today() method.

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

THE FILE SYSTEM

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

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

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

Work with file• open:create, open, and modify files• remove: delete filesCode Example:

import osfi = open(file)fo = open(temp,”w”) #w mean write permissonfor s in fi.readlines():

fo.write(s)fi.closefo.closeos.remove(back)

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

Work with directory

• listdir,chdir,mkdir,rmdir,getcwd: Please guess the function by the name

import osos.getpwd() # get the current diros.chdir(‘..’) # change to the parent directory

os.getcwd()os.listdir(‘.’) #list the file under the diros.mkdir(‘./temp1’) #make new dir

os.rmdir(‘./temp1’) #delete the diros.listdir(‘.’) # check if the delete is successful

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

Work with directory - cont

• removedirs,makedirs: remove and create directory hierarchies. Instead, rmdir and mkdir only handle single directory level.

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

Work with file attributes

• stat: It returns a 9-tuple which contains thesize, inode change timestamp, modification timestamp, and access privileges of a file. Similar as unix stat.

import osfile = "samples/sample.jpg“

st = os.stat(file)size = st[6] #file size

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

Working with processes

• system:runs a new command under the current process, and waits for it to finish

import osos.system('dir')os.system('notepad') # open notepad

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

The os.path class• This module contains functions that deal with long filenames (path

names) in various ways. • Learn from example

import osfilename = "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))

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

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

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

os.environ

• A mapping object representing the string environment. => key value pairs

a = os.environdir(a) # show all the functions of a a.keys() #show all the keysa.has_key('USERNAME') #check if has this keyprint a['USERNAME‘] # return the value of this key

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

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

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

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]

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

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.

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

Use TemporaryFile create temp file>>> import tempfile

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

Another example

• Write something into temp file. • Use seek() back to the beginning of file. Then

read it

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

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

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

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

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

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.

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

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

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

THE SYS MODULE

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

Brief introduction

• This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter.

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

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.pyimport sysprint "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”

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

Working with modules

• path: The path list contains a list of directory names where Python looks for extension modules

import syssys.path

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

sys.platform

• The platform variable contains the name of the host platform

import syssys.platform

• Typical platform names are win32 for Windows

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

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.stdoutf = open(‘file1.txt’,’w’)Sys.stdout = f #change the stdout to file1.txtprint “hello,world” sys.stdout = saveout

In this example, “hello,world” string has written to file1.txt.

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

sys.exit:Exiting the program

• This function takes an optional integer value, which is returned to the calling program.

import sysprint "hello"sys.exit(1)print "there"