5 个常用 Python 标准库

sys 获取程序参数、版本信息、模块搜索路径、标准输入输出等
os 操作文件,环境变量, os.patch路径信息处理

1、sys

>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_getframe', '_home', '_mercurial', '_xoptions', 'abiflags', 'api_version', 'argv', 'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'get_coroutine_wrapper', 'getallocatedblocks', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info', 'intern', 'is_finalizing', 'last_traceback', 'last_type', 'last_value', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'set_coroutine_wrapper', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout', 'thread_info', 'version', 'version_info', 'warnoptions']

sys.argv
获取命令行参数,list对象

import sys
print('len = ', len(sys.argv), 'argvs: ', sys.argv)

$ python3 mypython.py 1 2 3
len =  4 argvs:  ['mypython.py', '1', '2', '3']

sys.exit(n)
对出程序

>>> sys.exit(2)
$
>>> sys.version
'3.5.2 (default, Apr 16 2020, 17:47:17) \n[GCC 5.4.0 20160609]'
>>> sys.maxsize   #获取最大的Int值
9223372036854775807
>>> sys.path  #返回模块的搜索路径,append
['', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/home/xxx/.local/lib/python3.5/site-packages', '/usr/local/lib/python3.5/dist-packages', '/usr/local/lib/python3.5/dist-packages/pygame-1.9.4.dev0-py3.5-linux-x86_64.egg', '/usr/lib/python3/dist-packages']
>>> sys.platform
'linux'
>>> sys.moudles #返回模块字典

sys.stdout, sys.stdin, sys.stderror
分别和输出输入,错误输出相关

>>> import sys
>>> sys.stdout.write('ab')
ab2

重定向

import sys
file1 = sys.stdout
sys.stdout = open('1.txt','a')
print('abc')
sys.stdout.close()
sys.stdout = file1
print('cd')

>>> import mypython
cd

2、os 模块

>>> dir(os)
['CLD_CONTINUED', 'CLD_DUMPED', 'CLD_EXITED', 'CLD_TRAPPED', 'EX_CANTCREAT', 'EX_CONFIG', 'EX_DATAERR', 'EX_IOERR', 'EX_NOHOST', 'EX_NOINPUT', 'EX_NOPERM', 'EX_NOUSER', 'EX_OK', 'EX_OSERR', 'EX_OSFILE', 'EX_PROTOCOL', .....

```python
>>> os.system('ls')
1.txt  mypython.py  __pycache__
0
>>> os.remove('1.txt')
>>> os.getenv('PATH')
'/home/xxx/bin:/home/xxx/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin'
>>> os.putenv('a','123')

os.getcwd()
‘/home/xxx/Templates/pystruct’

os.listdir() #当前路径下 os.listdir(os.getcwd())
[‘1.txt’, ‘mypython.py’, ‘pycache’, ‘.mypython.py.swp’]

os.listdir(’/home’) #参数绝对路径
[‘xxx’]


```python
>>> os.path.abspath('mypython.py')   #获取文件的绝对路径
'/home/xxx/Templates/pystruct/mypython.py'
>>> os.path.abspath('.')
'/home/xkq3/Templates/pystruct'
>>> os.path.split('/home/xkq3/Templates/pystruct')   #将路径和文件分开
('/home/xkq3/Templates', 'pystruct')
>>> os.path.join('/home/xkq3/Templates','pystruct')   #将路径和文件合并
'/home/xkq3/Templates/pystruct'
>>> os.path.dirname('/home/xkq3/Templates/pystruct')  #获取路径部分
'/home/xkq3/Templates'
>>> os.path.basename('/home/xkq3/Templates/pystruct')   #获取文件部分 
'pystruct'
>>> os.path.getsize('/home/xkq3/Templates/pystruct')   #获取大小
4096
>>> os.path.exists('/home/xkq3/Templates/pystruct')   #判断是否存在
True
>>> os.path.getmtime('/home/xkq3/Templates/pystruct')   #最后修改时间
1590313706.1093626
>>> os.path.getatime('/home/xkq3/Templates/pystruct')   #最后访问时间
1590313706.1453485
>>> os.path.getctime('/home/xkq3/Templates/pystruct')   #最后创建时间
1590313706.1093626

3、time模块

https://blog.csdn.net/qq_41573234/article/details/82533820

>>> dir(time)
['CLOCK_MONOTONIC', 'CLOCK_MONOTONIC_RAW', 'CLOCK_PROCESS_CPUTIME_ID', 'CLOCK_REALTIME', 'CLOCK_THREAD_CPUTIME_ID', '_STRUCT_TM_ITEMS', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'altzone', 'asctime', 'clock', 'clock_getres', 'clock_gettime', 'clock_settime', 'ctime', 'daylight', 'get_clock_info', 'gmtime', 'localtime', 'mktime', 'monotonic', 'perf_counter', 'process_time', 'sleep', 'strftime', 'strptime', 'struct_time', 'time', 'timezone', 'tzname', 'tzset']
>>> time.time()   #返回当前时间的时间戳(从1970年1月1日00时00分00秒到现在的浮点秒数)
1590315462.593083
>>> time.localtime()  #当前当地时间
time.struct_time(tm_year=2020, tm_mon=5, tm_mday=24, tm_hour=3, tm_min=17, tm_sec=49, tm_wday=6, tm_yday=145, tm_isdst=1)

>>> time.gmtime()   #当前UTC时间
time.struct_time(tm_year=2020, tm_mon=5, tm_mday=24, tm_hour=10, tm_min=20, tm_sec=24, tm_wday=6, tm_yday=145, tm_isdst=0)
>>> time.gmtime(1590315462.593083)
time.struct_time(tm_year=2020, tm_mon=5, tm_mday=24, tm_hour=10, tm_min=17, tm_sec=42, tm_wday=6, tm_yday=145, tm_isdst=0)

>>> time.mktime(time.localtime())
1590315811.0

>>> time.asctime(time.localtime())
'Sun May 24 03:24:27 2020'
>>> time.ctime(1590315462.593083)
'Sun May 24 03:17:42 2020'

>>> time.sleep(3)

>>> time.clock()   #以浮点数计算的秒数返回当前的  CPU  (处理器)时间。用来衡量不同程序的耗时,比time.time()更有用
0.559493

4、random 模块

>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_BuiltinMethodType', '_MethodType', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_acos', '_ceil', '_cos', '_e', '_exp', '_inst', '_log', '_pi', '_random', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']

当每次生成随机数之前,如果设置seed的值相同,则随机数一样;默认seed(),种子不一样

>>> random.seed(1)
>>> random.random()
0.13436424411240122
>>> random.random()
0.8474337369372327
>>> random.seed(1)
>>> random.random()
0.13436424411240122

>>> random.random()   #随机浮点数
0.05629836895964435
>>> random.uniform(2,10)
5.445687343893744

>>> random.randint(2,10)  #随机整数
3
>>> random.randrange(2,10,2)
4

>>> random.choice('adsffv')   #随机字符串
's'
>>> random.choice(['a',1,3])
'a'
>>> random.sample('adsffv',3)
['f', 'v', 'a']

5、re模块

>>> dir(re)
['A', 'ASCII', 'DEBUG', 'DOTALL', 'I', 'IGNORECASE', 'L', 'LOCALE', 'M', 'MULTILINE', 'S', 'Scanner', 'T', 'TEMPLATE', 'U', 'UNICODE', 'VERBOSE', 'X', '_MAXCACHE', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '__version__', '_alphanum_bytes', '_alphanum_str', '_cache', '_cache_repl', '_compile', '_compile_repl', '_expand', '_locale', '_pattern_type', '_pickle', '_subx', 'compile', 'copyreg', 'error', 'escape', 'findall', 'finditer', 'fullmatch', 'match', 'purge', 'search', 'split', 'sre_compile', 'sre_parse', 'sub', 'subn', 'sys', 'template']

https://www.runoob.com/python/python-reg-expressions.html
re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。

>>> re.match('www', 'www.baidu.com').group()
'www'
>>> re.match('com', 'www.runoob.com')

>>> re.search('com', 'www.runoob.com')
<_sre.SRE_Match object; span=(11, 14), match='com'>

>>> re.match( r'(.*) are (.*?) .*', 'Cats are smarter than dogs', re.M|re.I)
<_sre.SRE_Match object; span=(0, 26), match='Cats are smarter than dogs'>
>>> re.match( r'(.*) are (.*?) .*', 'Cats are smarter than dogs', re.M|re.I).group(1)
'Cats'


>>> re.sub(r'#.*','',"2004-959-559 # 这是一个国外电话号码")
'2004-959-559 '
>>> re.sub(r'\D','',"2004-959-559 # 这是一个国外电话号码")
'2004959559'

正则表达式修饰符 - 可选标志

>>> def double(match):
...     value = int(match.group('value'))
...     return str(2*value)
... 
>>> re.sub('(?P\d)', double, '123abc456')
'246abc81012'


>>> pattern = re.compile(r'\d')
>>> pattern.match('123abc')
<_sre.SRE_Match object; span=(0, 1), match='1'>
>>> 

>>> pattern.findall('123abc')
['1', '2', '3']
>>> pattern.finditer('123abc')
<callable_iterator object at 0x7f1e9c28ada0>

>>> pattern.split('1a2b3abc')
['', 'a', 'b', 'abc']

你可能感兴趣的:(python)