Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the operation methods of Python standard library

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains the "what are the operating methods of the Python standard library", the content of the explanation is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "what are the operating methods of the Python standard library?"

1. Operating system interface

The os module provides a number of functions associated with the operating system.

> import os > os.getcwd () # returns the current working directory'C:\\ Python34' > os.chdir ('/ server/accesslogs') # modifies the current working directory > os.system ('mkdir today') # executes the system command mkdir 0

It is recommended to use the "import os" style instead of "from os import *". This ensures that os.open (), which varies from operating system to operating system, does not overwrite the built-in function open ().

Os common commands

The ordinal method function 1os.access (path, mode) verifies that the permission mode 2os.chdir (path) changes the mark of the current working directory 3os.chflags (path, flags) setting path to a digital mark. 4os.chmod (path, mode) change permissions 5os.chown (path, uid, gid) change file owner 6os.chroot (path) change the root directory of the current process 7os.close (fd) turn off file descriptors fd8os.closerange (fd_low, fd_high) close all file descriptors From fd_low (inclusive) to fd_high (not included), errors ignore 9os.dup (fd) copy file descriptor fd10os.dup2 (fd, fd2) copy one file descriptor fd to another fd22, file wildcard

The 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'] 3, command line arguments

Common tool scripts often call command-line arguments. These command-line parameters are stored as a linked list in the argv variable of the sys module.

Sys.argv

You can use sys.argv to get the parameter list (list) of the currently executing command-line arguments.

Variable interpretation

Sys.argv [0] current program name

The first parameter of sys.argv [1]

Second parameter of sys.argv [2]

Number of len (sys.argv)-1 parameters (minus file name)

For example, after executing "python demo.py one two three" on the command line, you can get the following output:

> import sys > print (sys.argv) ['demo.py',' one', 'two',' three'] 4, string regular matching

The re module provides regular expression tools for advanced string processing. It can be said that reptiles are essential, and regular expressions provide a concise and optimized solution for complex matching and processing: if only simple functions are needed, string methods should be considered first, because they are very simple and easy to read and debug:

> > 'tea for too'.replace (' too', 'two')' tea for two'

Re.match function

Re.match attempts to match a pattern from the beginning of the string, and match () returns none if the match is not successful.

Function syntax:

Re.match (pattern, string, flags=0)

Function parameter description:

Parameter describes the string to be matched by the regular expression string that pattern matches. Flags flag bit, which is used to control how regular expressions are matched, such as case sensitivity, multi-line matching, and so on.

If the match succeeds, the re.match method returns a matching object, otherwise it returns None.

We can use the group (num) or groups () match object function to get the matching expression.

The match object method describes the string of the entire expression that group (num=0) matches, and group () can enter more than one group number at a time, in which case it returns a tuple containing the values corresponding to those groups. Groups () returns a tuple containing all the team strings, from 1 to the contained group number. 5. Mathematical calculation

The math module provides access to the underlying C function library for floating-point operations:

> import math > math.cos (math.pi / 4) 0.70710678118654757 > math.log (1024, 2) 10.0

In practical work, the math standard library often can not meet the needs, I also need to extend the library: NumPy

NumPy (Numerical Python) not only supports a large number of dimensional array and matrix operations, but also provides a large number of mathematical function libraries for array operations.

NumPy official website NumPy

6. Send mail

There are several modules for accessing the Internet and dealing with network communication protocols. The two simplest of these are urllib.request for processing data received from urls and smtplib for sending e-mail:

Import smtplibsmtpObj = smtplib.SMTP ([host [, port [, local_hostname])

Parameter description:

Host: SMTP server host. You can specify the ip address or domain name of the host, such as runoob.com, which is an optional parameter.

Port: if you provide the host parameter, you need to specify the port number used by the SMTP service. Typically, the SMTP port number is 25.

Local_hostname: if SMTP is on your local computer, you only need to specify the server address as localhost.

The Python SMTP object uses the sendmail method to send messages with the following syntax:

SMTP.sendmail (from_addr, to_addrs, msg [, mail_options, rcpt_options])

Parameter description:

From_addr: address of the sender of the mail.

To_addrs: list of strings, email address.

Msg: sending messa

Case study:

#! / usr/bin/python#-*-coding: UTF-8-*-import smtplibfrom email.mime.text import MIMETextfrom email.header import Header sender = 'from@runoob.com'receivers = [' 429240967 email qq.com'] # to receive email, you can set it to your QQ Mail or other mailbox # three parameters: the first is text content, and the second plain is text format The third utf-8 setting code message = MIMEText ('Python mail sending test', 'plain',' utf-8') message ['From'] = Header ("rookie tutorial",' utf-8') # sender message ['To'] = Header ("test",' utf-8') # receiver subject = 'Python SMTP mail test' message ['Subject'] = Header (subject) 'utf-8') try: smtpObj = smtplib.SMTP (' localhost') smtpObj.sendmail (sender, receivers, message.as_string ()) print "message sent successfully" except smtplib.SMTPException: print "Error: unable to send message" 7, date and time

The datetime module provides both simple and complex methods for date and time processing.

While supporting date and time algorithms, the implementation focuses on more efficient processing and formatting output.

The module also supports time zone processing:

> # dates are easily constructed and formatted > > from datetime import date > now = date.today () > nowdatetime.date (2003, 12,2) > now.strftime ("% m-%d-%y.% d% Y is a% An on the% d day of% B.")'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'

There are three ways of existence of time: time object, time string and timestamp.

(1) convert string to datetime:

> string = '2014-01-08 11 datetime.datetime.strptime 59 string,'%Y-%m-%d 58' > time1 = datetime.datetime.strptime (string,'%Y-%m-%d% HV% MV% S') > print time12014-01-08 11:59:58

(2) convert datetime to string:

> time1_str = datetime.datetime.strftime (time1,'%Y-%m-%d% Hpurs% MVR% S') > time1_str'2014-01-08 11purl 59pur58'

(3) timestamp turns the time object:

> time1 = time.localtime () > time1_str = datetime.datetime.fromtimestamp (time1) 8, data compression

The following modules directly support common data packaging and compression formats: zlib,gzip,bz2,zipfile, and 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) 2268059799, performance measurement

Some users are interested in understanding the performance differences between different ways to solve the same problem. Python provides a measurement tool that provides direct answers to these questions.

For example, using tuple encapsulation and unwrapping to exchange elements seems much more attractive than using traditional methods, and timeit proves that modern methods are faster.

> from timeit import Timer > Timer ('tweea; astatbbbbbbbbbb.com, timeit () 0.57535828626024577 > > Timer () 0.54962537085770791)

Compared to the fine-grained timeit, the: mod:profile and pstats modules provide time measurement tools for larger blocks of code.

10. Test module

One of the ways to develop high-quality software is to develop test code for each function and test it frequently during the development process.

The doctest module provides a tool to scan the module and perform tests based on the document strings embedded in the program.

The test construct is as simple as cutting and pasting its output into a document string.

Through the example provided by the user, it strengthens the document and allows the doctest module to confirm that 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 doctestdoctest.testmod () # automatic verification embedding test Thank you for your reading. These are the contents of "how to operate the Python Standard Library". After the study of this article, I believe you have a deeper understanding of the operation methods of the Python Standard Library. The specific use situation still needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report