Python3.x Python3 Standard Library Overview
\n\nThe Python standard library is very extensive, providing a wide range of components. Using the standard library allows you to easily accomplish various tasks.
\n\nHere are some modules in the Python3 standard library:
\n\n- \n
- os module: The os module provides many functions for interacting with the operating system, such as creating, moving, and deleting files and directories, as well as accessing environment variables. \n
- sys module: The sys module provides functions related to the Python interpreter and the system, such as the interpreter's version and path, and information related to stdin, stdout, and stderr. \n
- time module: The time module provides functions for handling time, such as getting the current time, formatting dates and times, and timing. \n
- datetime module: The datetime module provides more advanced date and time handling functions, such as handling time zones, calculating time differences, and calculating date differences. \n
- random module: The random module provides functions for generating random numbers, such as generating random integers, floats, and sequences. \n
- math module: The math module provides mathematical functions, such as trigonometric functions, logarithmic functions, exponential functions, and constants. \n
- re module: The re module provides regular expression handling functions, which can be used for text searching, replacing, splitting, etc. \n
- json module: The json module provides JSON encoding and decoding functions, which can convert Python objects to JSON format and parse Python objects from JSON format. \n
- urllib module: The urllib module provides functions for accessing web pages and handling URLs, including downloading files, sending POST requests, handling cookies, etc. \n
Operating System Interface
\n\nThe os module provides many functions related to the operating system, such as file and directory operations.
\n\nExample
\n\nimport os\n\n# Get the current working directory.\n\n current_dir =os.getcwd()\n\nprint("Current working directory.:", current_dir)\n\n# List files in the directory.\n\n files =os.listdir(current_dir)\n\nprint("Files in the directory.:", files)\n\nIt is recommended to use the import os style rather than from os import *, as this ensures that the os.open() function, which may vary with the operating system, does not override the built-in open() function.
The built-in dir() and help() functions are very useful when using large modules like os:
>>> import os\n>>> dir(os)\n\n>>> help(os)\n \n\nFor daily file and directory management tasks, the shutil module provides an easy-to-use high-level interface:
>>> import shutil\n>>> shutil.copyfile('data.db', 'archive.db')\n>>> shutil.move('/build/executables', 'installdir')\n\n\n\n
File Wildcards
\n\nThe glob module provides a function for generating file lists from directory wildcard searches:
Example
\n\n>>>import glob\n\n>>>glob.glob('*.py')\n\n['primes.py','random.py','quote.py']\n\n\n\n
Command Line Arguments
\n\nGeneral-purpose utility scripts often invoke command line arguments. These command line arguments are stored in the argv variable of the sys module as a linked list. For example, after executing "python demo.py one two three" on the command line, you can get the following output:
Example
\n\n>>>import sys\n\n>>>print(sys.argv)\n\n['demo.py','one','two','three']\n\n\n\n
Error Output Redirection and Program Termination
\n\nThe sys module also has stdin, stdout, and stderr attributes. The latter can be used to display warning and error messages even when stdout is redirected.
Example
\n\n>>>sys.stderr.write('Warning, log file not found starting a new one\\n')\n\nWarning, log file not found starting a new one\n\nMost scripts terminate with sys.exit().
\n\n
String Regular Expression Matching
\n\nThe re module provides regular expression tools for advanced string processing. For complex matching and processing, regular expressions provide a concise and optimized solution:
\n\nExample
\n\n>>>import re\n\n>>>re.findall(r'\\b f*','which foot or hand fell fastest')\n\n['foot','fell','fastest']\n\n>>>re.sub(r'(\\b+) \\1', r'\\1','cat in the the hat')\n\n'cat in the hat'\n\nIf only simple functionality is needed, string methods should be considered first, as they are very simple, easy to read, and debug:
\n\n>>> 'tea for too'.replace('too', 'two')\n'tea for two'\n\n\n\n
Mathematics
\n\nThe math module provides access to the underlying C function library for floating-point operations:
\n\nExample
\n\n>>>import math\n\n>>>math.cos(math.pi / 4)\n\n0.70710678118654757\n\n>>>math.log(1024,2)\n\n10.0\n\nrandom provides tools for generating random numbers.
\n\nExample
\n\n>>>import random\n\n>>>random.choice(['apple','pear','banana'])\n\n'apple'\n\n>>>random.sample(range(100),10)# sampling without replacement\n\n[30,83,16,4,8,81,41,50,18,33]\n\n>>>random.random()# random float\n\n0.17970987693706186\n\n>>>random.randrange(6)# random integer chosen from range(6)\n\n4\n\n\n\n
Internet Access
\n\nThere are several modules for accessing the Internet and handling network communication protocols. The two simplest are urllib.request for handling data received from URLs and smtplib for sending emails:
Example
\n\n>>>from urllib.request import urlopen\n\n>>>for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):\n\n ... line= line.decode('utf-8')# Decoding the binary data to text.\n\n ... if'EST'in line or'EDT'in line: # look for Eastern Time\n\n ... print(line)\n\n
Nov. 25,09:43:32 PM EST\n\n>>>import smtplib\n\n>>> server =smtplib.SMTP('localhost')\n\n>>> server.sendmail('soothsayer@example.org','jcaesar@example.org',\n\n ... """To: jcaesar@example.org\n\n ... From: soothsayer@example.org\n\n ...\n\n ... Beware the Ides of March.\n\n ... """)\n\n>>> server.quit()\n\nNote that the second example requires a running mail server locally.
\n\n\n\n
Date and Time
\n\nThe datetime module provides both simple and complex methods for date and time handling.
\n\nWhile supporting date and time algorithms, the implementation focuses on more efficient processing and formatted output.
\n\nExample
\n\nimport datetime\n\n#Get Current date.and time\n\n current_datetime =datetime.datetime.now()\n\nprint(current_datetime)\n\n# Get Current date.\n\n current_date =datetime.date.today()\n\nprint(current_date)\n\n# Format date.\n\n formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")\n\nprint(formatted_datetime)# Output: 2023-07-17 15:30:45\n\nThe output is:
\n\n2023-07-17 18:37:56.036914\n2023-07-17\n2023-07-17 18:37:56\n\nThis module also supports time zone handling:
\n\n>>> # Imported the date class from the datetime module.\n>>> from datetime import date\n>>> now = date.today() # Current date.\n>>> now\ndatetime.date(2023, 7, 17)\n>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")\n'07-17-23. 17 Jul 2023 is a Monday on the 17 day of July.'\n>>> # Created a date object representing a birthday.\n>>> birthday = date(1964, 7, 31)\n>>> age = now - birthday # Calculate the time difference between two dates.\n>>> age.days # The days attribute of variable age, indicating the number of days in the time difference.\n21535\n\n\n\n
Data Compression
\n\nThe following modules directly support common data packing and compression formats: zlib, gzip, bz2, zipfile, and tarfile.
>>> import zlib\n>>> s = b'witch which has which witches wrist watch'\n>>> len(s)\n41\n>>> t = zlib.compress(s)\n>>> len(t)\n37\n>>> zlib.decompress(t)\nb'witch which has which witches wrist watch'\n>>> zlib.crc32(s)\n226805979\n\n\n\n
Performance Measurement
\n\nSome users are interested in understanding the performance differences between different methods for solving the same problem. Python provides a measurement tool that gives direct answers to these questions.
\n\nFor example, using tuple packing and unpacking to swap elements seems much more tempting than using traditional methods, and timeit proves that the modern method is slightly faster.
>>> from timeit import Timer\n>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()\n0.57535828626024577\n>>> Timer('a,b = b,a', 'a=1; b=2').timeit()\n0.54962537085770791\n\nCompared to the fine-grained timeit, the profile and pstats modules provide time measurement tools for larger code blocks.
\n\n
Testing Modules
\n\nOne way to develop high-quality software is to develop test code for each function and test frequently during the development process.
\n\nThe doctest module provides a tool that scans a module and executes tests based on the embedded docstrings in the program.
Test construction is as simple as cutting and pasting its output into the docstring.
\n\nThrough user-provided examples, it reinforces documentation and allows the doctest module to confirm whether the code's results match the documentation:
def average(values):\n """Computes the arithmetic mean of a list of numbers.\n\n >>> print(average([20, 30, 70]))\n 40.0\n """\n return sum(values) / len(values)\n\nimport doctest\ndoctest.testmod() # Automatically verify embedded test.\n\nThe unittest module is not as easy to use as the doctest module, but it can provide a more comprehensive test set in a separate file:
import unittest\n\nclass TestStatisticalFunctions(unittest.TestCase):\n\n def test_average(self):\n self.assertEqual(average([20, 30, 70]), 40.0)\n self.assertEqual(round(average([1, 5, 7]), 1), 4.3)\n self.assertRaises(ZeroDivisionError, average, [])\n self.assertRaises(TypeError, average, 20, 30, 70)\n\nunittest.main() # Calling from the command line invokes all tests\n\nWhat we've seen above is only a part of the Python3 standard library. Many other modules can be found in the official documentation: https://docs.python.org/zh-cn/3/library/index.html
YouTip