10.1. Operating System Interface
The
os
module provides dozens of functions for interacting with the operating system
os.getcwd()
, get current working directory.1
2# Return the current working directory os.getcwd()
'C:\\Python39'os.chdir()
, change current working directory1
2
3'/') os.chdir(
os.getcwd()
'/'os.system('cmd')
, run a cmd in system shell.1
2
3'ls') os.system(
....
0Be sure to use the
import os
style instead offrom os import *
. This will keepos.open()
from shadowing the built-inopen()
function which operates much differently.If you don’t know how to use a module, you can use
help(modulename)
to check the manual or The Python Standard Library
For daily file and directory management tasks, the
shutil
module provides a higher level interface that is easier to use
the shutil
stand for shell utilities
1 | import shutil |
10.2. File Wildcards
The
glob
module provides a function for making file lists from directory wildcard searches
A wildcard is a symbol such as \ or ? used in some computing commands or searches in order to represent any character or range of characters.*
1 | import glob |
- A glob pattern is a text expression that matches one or more file names using wild cards familiar to most users of a command line. For example,
*
is a glob that matches any name at all. Andglob
is a Filename globbing utility. - There are only three functions in this module, you can learn it quickly.
10.3. Command Line Arguments
- As has mentioned before, cmd arguments are stored in
sys.argv
- The
argparse
module provides a more sophisticated mechanism to process command line arguments. argparse
will be useful if you want to write some cmdline tools
10.4. Error Output Redirection and Program Termination
Use
sys.stderr
to prevent error massage from being redirected.1
2import sys
sys.stderr.write('Error!\n')1
2$ python3 ptest.py > trash
Error!you can use
sys.stderr
as a file1
2
3
4import sys
open('temp' , 'w+') file =
type(sys.stderr) == type(file)
TrueThe most direct way to terminate a script is to use
sys.exit()
.1
2
3
4
5
6
7exit(status=None, /)
Exit the interpreter by raising SystemExit(status).
If the status is omitted or None, it defaults to zero (i.e., success).
If the status is an integer, it will be used as the system exit status.
If it is another kind of object, it will be printed and the system
exit status will be one (i.e., failure).10.5. String Pattern Matching
use
re
for regular expressionfor simple string operation, use string methods like
s.replace('old','new')
10.6. Mathematics
The
math
module gives access to the underlying C library functions for floating point math
The
random
module provides tools for making random selections
The
statistics
module calculates basic statistical properties (the mean, median, variance, etc.) of numeric data
If these modules can not meet your requests, have a look at SciPy
10.7. Internet Access
There are a number of modules for accessing the internet and processing internet protocol.
Two of the simplest are:
urllib.request
—- retrive data from url (requests
can be more handy)smtplib
—-send emails(need a mail server running)1
2$ sudo python -m smtpd -n -c DebuggingServer localhost:25
# set up a fake server for debugging1
2
3
4
5
6
7
8
9import smtplib
server = smtplib.SMTP('localhost')
server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
"""To: jcaesar@example.org
From: soothsayer@example.org
Beware the Ides of March.
""")
server.quit()1
2
3
4
5
6
7
8$ python3 ptest.py
---------- MESSAGE FOLLOWS ----------
To: jcaesar@example.org
From: soothsayer@example.org
X-Peer: 127.0.0.1
Beware the Ides of March.
------------ END MESSAGE ------------10.8. Dates and Times
The
datetime
module supplies classes for manipulating dates and times in both simple and complex ways.
+
-
are supported.
1 | # get date of today |
10.9. Data Compression
Common data archiving and compression formats are directly supported by modules including:
zlib
,gzip
,bz2
,lzma
,zipfile
andtarfile
.
1 | import zlib |
10.10. Performance Measurement
knowing the relative performance of different approaches to the same problem.
use
timeit
for simple tests1
2
3
4
5from timeit import Timer
't=a; a=b; b=t', 'a=1; b=2').timeit() Timer(
0.57535828626024577
'a,b = b,a', 'a=1; b=2').timeit() Timer(
0.54962537085770791In contrast to
timeit
’s fine level of granularity, theprofile
andpstats
modules provide tools for identifying time critical sections in larger blocks of code.*
10.11. Quality Control
One approach for developing high quality software is to write tests for each function as it is developed and to run those tests frequently during the development process.
doctest
, scanning a module and validating tests embedded in a program’s docstrings.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
32
33def average(values):
"""Computes the arithmetic mean of a list of numbers.
>>> print(average([20, 30, 70]))
40.0
"""
return sum(values) / len(values)
import doctest
# automatically validate the embedded tests doctest.testmod()
TestResults(failed=0, attempted=1)
def average(values):
"""Computes the arithmetic mean of a list of numbers.
>>> print(average([20, 30, 7]))
40.0
"""
return sum(values) / len(values)
doctest.testmod()
**********************************************************************
File "__main__", line 4, in __main__.average
Failed example:
print(average([20, 30, 7]))
Expected:
40.0
Got:
19.0
**********************************************************************
1 items had failures:
1 of 1 in __main__.average
***Test Failed*** 1 failures.
TestResults(failed=1, attempted=1)unittest
, allows a more comprehensive set of tests to be maintained in a separate file.
10.12. Batteries Included
Python has a “batteries included” philosophy.
It means that something is self-sufficient, comes out-of-the-box ready to use, with everything that is needed.(开箱即用)
You can almost find every thing you need in The Python Standard Library.