python中常用到的模块和包名称

简介:

1 paramiko  (基于openssh,python封装的ssh)

模块python自带


用法:

1
2
3
4
5
6
7
8
9
10
11
12
13
import  paramiko                                          
ssh  =  paramiko.SSHClient()                               
ssh.load_system_host_keys()                              
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname = '192.168.100.20' ,port = 58422 ,username = 'oldboy' )
stdin, stdout,stderr = ssh.exec_command( 'uptime' )    
                 
type (stdout)
paramiko.ChannelFile
print  stderr.readlines()
[]
print  stdout.readlines()
[ ' 21:35:05 up 1 day, 55 min,  2 users,  load average: 0.00, 0.00, 0.00\n' ]


相当于shell当中的 

1
ssh  -p58422 oldboy@192.168.100.20 -o StrictHostKeyChecking=no  'uptime'


2 subprocess(尽量不要用这个模块,返回不美观,如果只是执行shell命令推荐commands模块) Python3

python自带模块 使用在python 3中取代python 2 中的commands模块

参考:http://www.jb51.net/article/48086.htm

常用fork子进程执行shell命令,可以返回结果和返回值

举例:
只需要返回值

1
2
3
4
5
6
7
In [ 6 ]: retcode  =  subprocess.call( 'ls -l' , shell = True )
total  12
- rw - rw - r - - 1  oldboy oldboy  239  Jan  19  21 : 13  access.log
- rw - rw - r - - 1  oldboy oldboy  458  Jan  19  20 : 50  arp.txt
- rw - r - - r - - 1  oldboy oldboy  184  Jan  16  12 : 04  hosts
In [ 7 ]:  print  retcode
0


注意: 

shell默认为False,等于 retcode = subprocess.call(["ls", "-l"])  列表的形式第一个为命令,后面的都作为参数传递


需要返回值

1
2
child1  =  subprocess.Popen([ "cat" , "/etc/passwd" ], stdout = subprocess.PIPE)
child1.stdout.readlines()

常用:

file="get_ldap_zhname.sh"

1
2
3
     child1  =  subprocess.Popen( 'sh '  +  file  +  ' ' +   um, shell = True , stdout = subprocess.PIPE)
     status  =  child1.wait()
     output  =  child1.stdout.read().strip()

3 comands模块(python 2中)

python自带模块

1
  status,output  =  commands.getstatusoutput( 'cat /etc/passwd' )

优点: 无论命令执行错误与正确,正确输出和错误输出都以字符串原样的字符串形式传递给output


4 multiprocessing模块

python自带模块

pool = multiprocessing.Pool(processes=4)

result_tmp.append(pool.apply_async(func, ( arg1,arg2,arg3)))



5 ping模块

pip install ping 

result = ping.quiet_ping(addr, timeout=2, count=5, psize=64)

loss_rate=result[0]

max_time=result[1]

average_time=result[2]


常用处理(取float的位数和把None值 变为0表示不通):

loss_rate = result[0]

max_time = float('%.3f'% result[1]) if isinstance(result[1], float) else 0

#if max_time and average_time is None use 0

average_time = float('%.3f'% result[2]) if isinstance(result[2], float) else 0



6 random模块

python自带

import random

常用函数

a. random函数 生成一个0-1的随机数

1
2
In [ 26 ]: random.random()
Out[ 26 ]:  0.6289910862564466



b.  sample 在一个列表(字符串)中随机抽样N个数,返回一个新的列表

1
2
3
4
In [ 27 ]: random.sample( xrange ( 1 , 100 ),  3 )
Out[ 27 ]: [ 94 91 53 ]
In [ 28 ]: random.sample( 'asdfasdf' 3 )
Out[ 28 ]: [ 'f' 'a' 'a' ]


c.  randint 函数,在指定的整数范围内(1<=x<=20),返回一个数

1
2
In [ 29 ]: random.randint( 1 , 20 )
Out[ 29 ]:  18



7 uuid模块

python自带

import uuid

常用: uuid1函数,通过mac和时间戳生成全球唯一的id

1
2
In [ 49 ]: uuid.uuid1()
Out[ 49 ]: UUID( 'cbb8c051-0929-11e6-9ba3-8c2937eebf3a' )


(注意是 UUID类型,经常转化为str类型)

1
2
In [ 50 ]:  str (uuid.uuid1())
Out[ 50 ]:  'cf296582-0929-11e6-8bbf-8c2937eebf3a'



8 hashlib 模块 

常用md5函数  (常结合uuid来生成一个32位的随机数)


1
2
In [ 48 ]: hashlib.md5( str (uuid.uuid1())).hexdigest()
Out[ 48 ]:  'd4aacc5bb29a24fd9db8e2ea1bf53cb7'



9 时间模块 time, datetime timedelta 

参考: http://cuidehua.blog.51cto.com/5449828/1767046

 


10 json模块

参考: http://cuidehua.blog.51cto.com/5449828/1767061



11 re 正则表达式模块

python自带

常用 判断一个字符串是否符合指定的表达式

1
2
3
4
5
6
7
8
In [ 9 ]:  import  re
In [ 10 ]: s  =  "10.1.1.223"
In [ 11 ]:  if  re.match(r "10.1" , s):
    ....:      print  "为10.1网段"
    ....:  else :
    ....:      print  "不在10.1网段"
    ....:     
10.1 网段


区别re.match()  和re.search()的区别

re.match(r“10.2,s”)   和  re.search(r”^10.2”,s)  是一样的

注:

1 匹配则返回对象本身,不匹配则放回None

2 match只匹配字符串的开始,如果开始不符合正则表达式,就返回None,而search匹配整个字符串,匹配到了则算匹配成功


12 collections 模块OrderedDict 函数

python自带内模块

作用: 定义有序字典,当有需要dict字典的key是有序的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
In [ 73 ]:  from  collections  import  OrderedDict
In [ 74 ]: od  =  OrderedDict()
In [ 75 ]: od[ 'key1' =  'value1'
In [ 76 ]: od[ 'key2' =  'value2' 
In [ 77 ]: od[ 'key3' =  'value3' 
In [ 78 ]: od
Out[ 78 ]: OrderedDict([( 'key1' 'value1' ), ( 'key2' 'value2' ), ( 'key3' 'value3' )])
In [ 79 ]: od.keys()
Out[ 79 ]: [ 'key1' 'key2' 'key3' ]
In [ 80 ]:  for  k,v  in  od.ite
od.items       od.iteritems   od.iterkeys    od.itervalues  
In [ 80 ]:  for  k,v  in  od.items():
    ....:      print  k,v
    ....:     
key1 value1
key2 value2
key3 value3



12 collections 模块Counter 函数

python再带内建(python 2.7 以上版本才有Counter函数)

Counter函数是属于字典的子类,所有也拥有字典相关的特性


重要用途: 返回列表(字符串)中元素出现的次数


1
2
3
In [ 11 ]:  from  collections  import  Counter
In [ 12 ]: l  =  [ 'a' , 'b' , 'a' , 'c' , 'a' , 'd' ]
In [ 13 ]: number_rep =  Counter(l)

返回的是keys和次数组成的字典

1
2
3
4
In [ 14 ]: number_rep
Out[ 14 ]: Counter({ 'a' 3 'b' 1 'c' 1 'd' 1 })
In [ 15 ]:  type (number_rep)
Out[ 15 ]: collections.Counter


拥有字典的大部分属性函数

1
2
In [ 16 ]: number_rep[ "a" ]
Out[ 16 ]:  3
1
2
In [ 18 ]: number_rep.keys()
Out[ 18 ]: [ 'a' 'c' 'b' 'd' ]

返回出现最多的key和次数组成的二元元组列表

1
2
In [ 19 ]: number_rep.most_common( 1 )
Out[ 19 ]: [( 'a' 3 )]


也有相加功能

1
2
3
4
5
In [ 21 ]: s  =  "efghfgfefda"
In [ 22 ]: Counter(s)
Out[ 22 ]: Counter({ 'a' 1 'd' 1 'e' 2 'f' 4 'g' 2 'h' 1 })
In [ 23 ]: number_rep  +  Counter(s)
Out[ 23 ]: Counter({ 'a' 4 'b' 1 'c' 1 'd' 2 'e' 2 'f' 4 'g' 2 'h' 1 })



注意:python 2.6环境中

pip install counter

from counter import Counter

13 linecache模块

python自带

import linecache


作用,读取文本行,大的文本,可以缓存到内存,下次再次读取直接从内存中拿取


用法:

返回所有行,以列表的形式

1
l_lines  =  linecache.getlines( 'filename' )

返回指定的一行,返回字符串形式

1
s_line  =  linecache.getline( 'filename' , linenumber).rstrip()

更新缓存,是直接从磁盘中读取文件,并更新内存中的缓存,返回列表形式的所有行

1
l_lines  =  linecache.updatecache( 'filename' )


更新缓存  所有拥有缓存的

1
linecache.checkcache()


或者 指定更新的文件

1
linecache.checkcache( 'filename' )

本文转自残剑博客51CTO博客,原文链接http://blog.51cto.com/cuidehua/1761922如需转载请自行联系原作者


cuizhiliang

相关文章
|
3月前
|
SQL 关系型数据库 数据库
Python SQLAlchemy模块:从入门到实战的数据库操作指南
免费提供Python+PyCharm编程环境,结合SQLAlchemy ORM框架详解数据库开发。涵盖连接配置、模型定义、CRUD操作、事务控制及Alembic迁移工具,以电商订单系统为例,深入讲解高并发场景下的性能优化与最佳实践,助你高效构建数据驱动应用。
418 7
|
3月前
|
监控 安全 程序员
Python日志模块配置:从print到logging的优雅升级指南
从 `print` 到 `logging` 是 Python 开发的必经之路。`print` 调试简单却难维护,日志混乱、无法分级、缺乏上下文;而 `logging` 支持级别控制、多输出、结构化记录,助力项目可维护性升级。本文详解痛点、优势、迁移方案与最佳实践,助你构建专业日志系统,让程序“有记忆”。
293 0
|
3月前
|
JSON 算法 API
Python中的json模块:从基础到进阶的实用指南
本文深入解析Python内置json模块的使用,涵盖序列化与反序列化核心函数、参数配置、中文处理、自定义对象转换及异常处理,并介绍性能优化与第三方库扩展,助你高效实现JSON数据交互。(238字)
418 4
|
3月前
|
Java 调度 数据库
Python threading模块:多线程编程的实战指南
本文深入讲解Python多线程编程,涵盖threading模块的核心用法:线程创建、生命周期、同步机制(锁、信号量、条件变量)、线程通信(队列)、守护线程与线程池应用。结合实战案例,如多线程下载器,帮助开发者提升程序并发性能,适用于I/O密集型任务处理。
335 0
|
3月前
|
XML JSON 数据处理
超越JSON:Python结构化数据处理模块全解析
本文深入解析Python中12个核心数据处理模块,涵盖csv、pandas、pickle、shelve、struct、configparser、xml、numpy、array、sqlite3和msgpack,覆盖表格处理、序列化、配置管理、科学计算等六大场景,结合真实案例与决策树,助你高效应对各类数据挑战。(238字)
230 0
|
4月前
|
安全 大数据 程序员
Python operator模块的methodcaller:一行代码搞定对象方法调用的黑科技
`operator.methodcaller`是Python中处理对象方法调用的高效工具,替代冗长Lambda,提升代码可读性与性能。适用于数据过滤、排序、转换等场景,支持参数传递与链式调用,是函数式编程的隐藏利器。
151 4
|
4月前
|
存储 数据库 开发者
Python SQLite模块:轻量级数据库的实战指南
本文深入讲解Python内置sqlite3模块的实战应用,涵盖数据库连接、CRUD操作、事务管理、性能优化及高级特性,结合完整案例,助你快速掌握SQLite在小型项目中的高效使用,是Python开发者必备的轻量级数据库指南。
370 0
|
5月前
|
数据处理 开发工具 开发者
requirement.txt 管理python包依赖
在 Python 项目中,`requirements.txt` 用于记录依赖库及其版本,便于环境复现。本文介绍了多种生成该文件的方法:基础方法使用 `pip freeze`,进阶方法使用 `pipreqs`,专业方法使用 `poetry` 或 `pipenv`,以及手动维护方式。每种方法适用不同场景,涵盖从简单导出到复杂依赖管理,并提供常见问题的解决方案,帮助开发者高效生成精准的依赖列表,确保项目环境一致性。
1437 4
|
5月前
|
存储 安全 数据处理
Python 内置模块 collections 详解
`collections` 是 Python 内置模块,提供多种高效数据类型,如 `namedtuple`、`deque`、`Counter` 等,帮助开发者优化数据处理流程,提升代码可读性与性能,适用于复杂数据结构管理与高效操作场景。
382 0
|
6月前
|
数据安全/隐私保护 Python
抖音私信脚本app,协议私信群发工具,抖音python私信模块
这个实现包含三个主要模块:抖音私信核心功能类、辅助工具类和主程序入口。核心功能包括登录

推荐镜像

更多