Python标准库使用

Python标准库使用

游戏|数码彩彩2024-06-11 7:37:53318A+A-

零基础编程——Python标准库使用

本文将讲解Python标准库内容,有操作系统接口os、文件路径通配符glob、命令行参数sys、正则表达式re、数学math、日期与时间、数据压缩、性能评估等,我们只需要知道有些什么内容,用到时候再查找资料即可,无需熟记,也记不住。

零基础编程——Python标准库使用

 

一 操作系统接口及文件通配符

1-路径操作

import os

os.getcwd()#获取当前路径

os.chdir('../')#改变当前路径

os.getcwd()#获取当前路径

2-不同操作系统有不同接口函数

有进程参数、文件创建、进程管理、调度等

具体参考:https://docs.python.org/3.6/library/os.html#module-os

3-文件通配符

import glob
glob.glob('*.py')#返回当前路径下所有py文件数组

适配查找文件

>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
>>> glob.glob('**/*.txt', recursive=True)
['2.txt', 'sub/3.txt']
>>> glob.glob('./**/', recursive=True)
['./', './sub/']

4-命令行参数

参考:https://docs.python.org/3.6/library/sys.html#module-sys

 

二 字符串匹配正则表达式

1-示例

>>> import re
>>> re.findall(r'bf[a-z]*', 'which foot or hand fell fastest')
#b表示匹配一个单词边界,也就是指单词和空格间的位置。 f开始的单词
['foot', 'fell', 'fastest']
>>> re.sub(r'(b[a-z]+) 1', r'1', 'cat in the the hat')
'cat in the hat'

2-正则表达式语法

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

 

零基础编程——Python标准库使用

 

更多参考:https://docs.python.org/3.6/library/re.html#module-re

 

三 数学计算与时间

1-math

涵括:数论计算、指数计算、三角函数、角度计算、双曲线、常量等

直接传入参数调用函数即可,比较简单,请参考:https://docs.python.org/3.6/library/math.html#module-math

import math
math.gamma(0.5)#伽马函数
math.pi#Π值

2-datetime

>>> # 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

四 数据压缩

常见数据压缩格式: zlib, gzip, bz2, lzma, 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)
226805979

五 多线程

模块:

  • _thread(3.6之后不兼容了)
  • threading(推荐使用)
零基础编程——Python标准库使用

 

import threading
import time

exitFlag = 0

class myThread (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print ("开始线程:" + self.name)
        print_time(self.name, self.counter, 5)
        print ("退出线程:" + self.name)

def print_time(threadName, delay, counter):
    while counter:
        if exitFlag:
            threadName.exit()
        time.sleep(delay)
        print ("%s: %s" % (threadName, time.ctime(time.time())))
        counter -= 1

# 创建新线程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

# 开启新线程
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print ("退出主线程")

Thread 对象的 Lock 和 Rlock 可以实现简单的线程同步,Python 的 Queue 模块中提供了同步的、线程安全的队列类,包括FIFO(先入先出)队列Queue,LIFO(后入先出)队列LifoQueue,和优先级队列 PriorityQueue。更多参考:https://www.runoob.com/python3/python3-multithreading.html

 

六 弱引用

为了提高性能,采用弱引用方式调用对象,当删除对象的时候,自动释放内存,引用失效。常用于创建对象耗时、缓存对象等。

>>> import weakref, gc
>>> class A:
...     def __init__(self, value):
...         self.value = value
...     def __repr__(self):
...         return str(self.value)
...
>>> a = A(10)                   # create a reference
>>> d = weakref.WeakValueDictionary()
>>> d['primary'] = a            # does not create a reference
>>> d['primary']                # fetch the object if it is still alive
10
>>> del a                       # remove the one reference
>>> gc.collect()                # run garbage collection right away
0
>>> d['primary']                # entry was automatically removed
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    d['primary']                # entry was automatically removed
  File "C:/python36/lib/weakref.py", line 46, in __getitem__
    o = self.data[key]()
KeyError: 'primary'

七 其他

还有logging日志,array、collections数组集合工具、decimal浮点数运算、reprlib输出格式等等

 

 

点击这里复制本文地址 版权声明:本文内容由网友提供,该文观点仅代表作者本人。本站(https://www.angyang.net.cn)仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件举报,一经查实,本站将立刻删除。

昂扬百科 © All Rights Reserved.  渝ICP备2023000803号-3网赚杂谈