os Module provides many functions associated with the operating system .
>>> import os >>> os.getcwd() # Return to the current working directory 'C:\\Python34' >>> os.chdir('/server/accesslogs') # Modify the current working directory >>> os.system('mkdir today') # Execute system commands mkdir 0
It is recommended to use "import os" Style rather than "from os import *". This ensures that the operating system will change os.open() Does not override built-in functions open().
In the use of os Such large modules are built-in dir() and help() Functions are very useful :
>>> import os >>> dir(os) <returns a list of all module functions> >>> help(os) <returns an extensive manual page created from the module's docstrings>
For daily file and directory management tasks ,:mod:shutil Module provides an easy to use high-level interface :
>>> import shutil >>> shutil.copyfile('data.db', 'archive.db') >>> shutil.move('/build/executables', 'installdir')
glob Module provides a function to generate a list of files from a directory wildcard search :
>>> import glob >>> glob.glob('*.py') ['primes.py', 'random.py', 'quote.py']
Common tool scripts often call command line arguments . These command line parameters are stored in the form of a linked list sys Modular argv Variable . For example, execute... On the command line "python demo.py one two three" After that, we can get the following output results :
>>> import sys >>> print(sys.argv) ['demo.py', 'one', 'two', 'three']
sys also stdin,stdout and stderr attribute , Even in stdout When redirected , The latter can also be used to display warning and error messages .
>>> sys.stderr.write('Warning, log file not found starting a new one\n') Warning, log file not found starting a new one
Most script directed terminations use "sys.exit()".
re Module provides regular expression tools for advanced string processing . For complex matching and processing , Regular expressions provide simplicity 、 Optimized solution :
>>> import re >>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest') ['foot', 'fell', 'fastest'] >>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat') 'cat in the hat'
If only simple functions are needed , You should first consider string methods , Because they are very simple , Easy to read and debug :
>>> 'tea for too'.replace('too', 'two') 'tea for two'
math Module for floating-point operations to provide the underlying C Access to function library :
>>> import math >>> math.cos(math.pi / 4) 0.70710678118654757 >>> math.log(1024, 2) 10.0
random Provides tools for generating random numbers .
>>> import random >>> random.choice(['apple', 'pear', 'banana']) 'apple' >>> random.sample(range(100), 10) # sampling without replacement [30, 83, 16, 4, 8, 81, 41, 50, 18, 33] >>> random.random() # random float 0.17970987693706186 >>> random.randrange(6) # random integer chosen from range(6) 4
There are several modules for accessing the Internet and dealing with network communication protocols . The simplest two of them are used to deal with from urls Of received data urllib.request And the smtplib:
>>> from urllib.request import urlopen >>> for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'): ... line = line.decode('utf-8') # Decoding the binary data to text. ... if 'EST' in line or 'EDT' in line: # look for Eastern Time ... print(line) <BR>Nov. 25, 09:43:32 PM EST >>> import smtplib >>> server = smtplib.SMTP('localhost') >>> server.sendmail('[email protected]', '[email protected]', ... """To: [email protected] ... From: [email protected] ... ... Beware the Ides of March. ... """) >>> server.quit()
Note that the second example requires a mail server running locally .
datetime Module provides both simple and complex methods for date and time processing .
Support date and time algorithm at the same time , Implementation focuses on more efficient processing and formatting of output .
The module also supports time zone processing :
>>> # dates are easily constructed and formatted >>> from datetime import date >>> now = date.today() >>> now datetime.date(2003, 12, 2) >>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.") '12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.' >>> # dates support calendar arithmetic >>> birthday = date(1964, 7, 31) >>> age = now - birthday >>> age.days 14368
The following modules directly support the general data packaging and compression format :zlib,gzip,bz2,zipfile, as well as tarfile.
>>> import zlib >>> s = b'witch which has which witches wrist watch' >>> len(s) 41 >>> t = zlib.compress(s) >>> len(t) 37 >>> zlib.decompress(t) b'witch which has which witches wrist watch' >>> zlib.crc32(s) 226805979
Some users are interested in understanding the performance differences between different ways to solve the same problem .Python Provides a measurement tool , Provides direct answers to these questions .
for example , Using tuple encapsulation and unpacking to exchange elements looks more attractive than using traditional methods ,timeit It turns out that modern methods are faster .
>>> from timeit import Timer >>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit() 0.57535828626024577 >>> Timer('a,b = b,a', 'a=1; b=2').timeit() 0.54962537085770791
be relative to timeit 's fine-grained ,:mod:profile and pstats Module provides a time measurement tool for larger blocks of code .
One of the ways to develop high-quality software is to develop test code for each function , And in the development process often test
doctest Module provides a tool , Scan the module and perform the test according to the document string embedded in the program .
The test construct is like simply cutting and pasting its output into a document string .
Through examples provided by users , It reinforces the documentation , allow doctest Module confirms whether the result of the code is consistent with the document :
def 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 doctest.testmod() # Automatic verification of embedded tests
unittest Modules don't look like doctest Modules are so easy to use , However, it can provide a more comprehensive test set in a separate file :
import unittest class TestStatisticalFunctions(unittest.TestCase): def test_average(self): self.assertEqual(average([20, 30, 70]), 40.0) self.assertEqual(round(average([1, 5, 7]), 1), 4.3) self.assertRaises(ZeroDivisionError, average, []) self.assertRaises(TypeError, average, 20, 30, 70) unittest.main() # Calling from the command line invokes all tests
Python3 Namespace / Scope
Python3 example
2 Notes Write notes
zhangxv
zha***[email protected]
Reference address
209
About urlopen A supplement to
# Handle get request , Don't pass on data, Then for get request import urllib from urllib.request import urlopen from urllib.parse import urlencode url='http://www.xxx.com/login' data={"username":"admin","password":123456} req_data=urlencode(data)# Transform the request data of dictionary type into url code res=urlopen(url+'?'+req_data)# adopt urlopen Method access spliced url res=res.read().decode()#read() The method is to read the contents of the returned data ,decode Is the data returned from the conversion bytes The format is str print(res) # Handle post request , If it does data, Then for post request import urllib from urllib.request import Request from urllib.parse import urlencode url='http://www.xxx.com/login' data={"username":"admin","password":123456} data=urlencode(data)# Transform the request data of dictionary type into url code data=data.encode('ascii')# take url The request data of the encoding type is transformed into bytes type req_data=Request(url,data)# take url And request data processing as a Request object , for urlopen call with urlopen(req_data) as res: res=res.read().decode()#read() The method is to read the contents of the returned data ,decode Is the data returned from the conversion bytes The format is str print(res)zhangxv
zhangxv
zha***[email protected]
Reference address
5 Years ago (2018-01-13)redhands
zho***[email protected]
Reference address
274
Time and date supplement
Common time processing methods
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
last_month = today.month - 1 if today.month - 1 else 12
time_stamp = time.time()
datetime.datetime.fromtimestamp(time_stamp)
int(time.mktime(today.timetuple()))
today_str = today.strftime("%Y-%m-%d")
today = datetime.datetime.strptime(today_str, "%Y-%m-%d")
today + datetime.timedelta(hours=8)