python基础之常用模块一(sys、greenlet、pymysql、paramiko、pexpect、configparser)
一、sys模块(内置模块)
用于提供对解释器相关的操作
import sys
sys.argv 命令行参数List,第一个元素是程序本身路径
sys.exit(n) 退出程序,正常退出时exit(0)
sys.version 获取Python解释程序的版本信息
sys.maxint 最大的Int值
sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform 返回操作系统平台名称
sys.stdout.write('please:')
val = sys.stdin.readline()[:-1]
sys模块更多用法:https://docs.python.org/2/library/sys.html?highlight=sys#module-sys
二、Greenlet模块
IO操作,即对硬盘上的数据进行读写操作。
greenlet只是提供了一种比generator更加便捷的切换方式,当切到一个任务执行时如果遇到IO,那就原地阻塞,仍然是没有解决遇到IO自动切换来提升效率的问题。
单线程里的这20个任务的代码通常会既有计算操作又有阻塞操作,我们完全可以在执行任务1时遇到阻塞,就利用阻塞的时间去执行任务2......如此,才能提高效率,这就用到了Gevent模块
from greenlet import greenlet #greenlet协程模块
# 定义吃
def eat():
print('eat-start')
g2.switch() #
print('eat-end')
# 定义玩
def play():
print('play happy')
g1.switch() # 切回对应的方法接着执行
g1 = greenlet(eat)
g2 = greenlet(play)
g1.switch()#可以在第一次switch时传入参数,以后都不需要;switch是切换的意思
输出:
eat-start
play happy
eat-end
三、paramiko模块
#通过paramiko模块连接主机运行bash命令 import paramiko
hostname = '192.168.254.24'
port = 22
username = 'root'
password = 'root'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=hostname,port=port,username=username,password=password)
stdin, stdout, stderr = ssh.exec_command("ls -ltr")
print(stdout.read().decode('utf-8')) #通过paramiko模块连接主机上传
import paramiko
hostname = '192.168.254.24'
port = 22
username = 'root'
password = 'root'
t=paramiko.Transport((hostname,port))
t.connect(username=username,password=password)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.put(r'C:\Users\fengzi\Desktop\Linux.xmind', '/root/aaa.xmind')
sftp.close() #通过paramiko模块连接主机下载
import paramiko
hostname = '192.168.254.24'
port = 22
username = 'root'
password = 'root'
t=paramiko.Transport((hostname,port))
t.connect(username=username,password=password)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.get('/root/test3.yml', r'C:\Users\fengzi\Desktop\test3.yml')
sftp.close()
四、pexpect模块
import pexpect
host = '192.168.254.24'
password = 'root'
username = 'root'
child = pexpect.spawn('ssh root@192.168.254.24')
child.expect('password:')
child.sendline(password)
child.expect('#')
child.sendline('mysql -uroot -proot')
child.expect('none')
child.sendline('show variables like "%log%";')
child.sendline('exit')
child.sendline('exit')
child.interact()
child.close() #利用pexpect查看其他机器的数据库
import pexpect
ssh = pexpect.spawn('ssh 192.168.254.12',timeout=10)
i = ssh.expect(['password:','continue connecting'],timeout=10)
print(i)
if i == 0:
ssh.sendline('root')
elif i == 1:
ssh.sendline('yes\n')
ssh.expect('password:')
ssh.sendline('root\n')
index = ssh.expect(['#',pexpect.EOF,pexpect.TIMEOUT],timeout=15)
if index == 0:
ssh.sendline('ip a')
ssh.sendline('exit')
ssh.interact()
ssh.close()
elif index == 1:
print('logging process exit')
elif index == 2:
print('logging in time out') #ssh登录主机
五、pymysql模块
#pymysql操作数据库
import pymysql
# 打开数据库连接
db = pymysql.connect(host="192.168.254.24", user="root",
password="root", db="mysql", port=3306) # 使用cursor()方法获取操作游标
cur = db.cursor() # 1.查询操作
# 编写sql 查询语句 user 对应我的表名
sql = "select host,user,password from user"
try:
cur.execute(sql) # 执行sql语句
results = cur.fetchall() # 获取查询的所有记录
for i in results:#遍历结果
print(i)
except Exception as e:
raise e
finally:
db.close() # 关闭连接
六、configparser模块
1、CconfigParser简介
ConfigParser 是用来读取配置文件的包。配置文件的格式如下:中括号“[ ]”内包含的为section。section 下面为类似于key-value 的配置内容。
[db]
db_host = 127.0.0.1
db_port = 69
db_user = root
db_pass = root
host_port = 69 [concurrent]
thread = 10
processor = 20
括号“[ ]”内包含的为section。紧接着section 为类似于key-value 的options 的配置内容。
2、ConfigParser 初始化对象
使用ConfigParser 首先需要初始化实例,并读取配置文件:
import configparser
config = configparser.ConfigParser()
config.read("info.txt", encoding="utf-8")
3、ConfigParser 常用方法
1、获取所用的section节点
# 获取所用的section节点
import configparser
config = configparser.ConfigParser()
config.read("info.txt", encoding="utf-8")
print(config.sections())
#运行结果
# ['db', 'concurrent'] 2、获取指定section 的options。即将配置文件某个section 内key 读取到列表中:
import configparser
config = configparser.ConfigParser()
config.read("info.txt", encoding="utf-8")
r = config.options("db")
print(r)
#运行结果
# ['db_host', 'db_port', 'db_user', 'db_pass', 'host_port'] 3、获取指点section下指点option的值
import configparser
config = configparser.ConfigParser()
config.read("info.txt", encoding="utf-8")
r = config.get("db", "db_host")
# r1 = config.getint("db", "k1") #将获取到值转换为int型
# r2 = config.getboolean("db", "k2" ) #将获取到值转换为bool型
# r3 = config.getfloat("db", "k3" ) #将获取到值转换为浮点型
print(r)
#运行结果
# 127.0.0.1 4、获取指点section的所用配置信息
import configparser
config = configparser.ConfigParser()
config.read("info.txt", encoding="utf-8")
r = config.items("db")
print(r)
#运行结果
#[('db_host', '127.0.0.1'), ('db_port', '69'), ('db_user', 'root'), ('db_pass', 'root'), ('host_port', '69')] 5、修改某个option的值,如果不存在则会出创建
# 修改某个option的值,如果不存在该option 则会创建
import configparser
config = configparser.ConfigParser()
config.read("info.txt", encoding="utf-8")
config.set("db", "db_port", "69") #修改db_port的值为69
config.write(open("info.txt", "w"))
#运行结果
6、检查section或option是否存在,bool值
import configparser
config = configparser.ConfigParser()
config.has_section("section") #是否存在该section
config.has_option("section", "option") #是否存在该option
7、添加section 和 option
import configparser
config = configparser.ConfigParser()
config.read("info.txt", encoding="utf-8")
if not config.has_section("default"): # 检查是否存在section
config.add_section("default")
if not config.has_option("default", "db_host"): # 检查是否存在该option
config.set("default", "db_host", "1.1.1.1")
config.write(open("info.txt", "w"))
#运行结果
8、删除section 和 option
import configparser
config = configparser.ConfigParser()
config.read("info.txt", encoding="utf-8")
config.remove_section("default") #整个section下的所有内容都将删除
config.write(open("info.txt", "w"))
#运行结果
9、写入文件
以下的几行代码只是将文件内容读取到内存中,进过一系列操作之后必须写回文件,才能生效。
import configparser
config = configparser.ConfigParser()
config.read("info.txt", encoding="utf-8")
写回文件的方式如下:(使用configparser的write方法)
config.write(open("info.txt", "w"))
python基础之常用模块一(sys、greenlet、pymysql、paramiko、pexpect、configparser)的更多相关文章
- 十八. Python基础(18)常用模块
十八. Python基础(18)常用模块 1 ● 常用模块及其用途 collections模块: 一些扩展的数据类型→Counter, deque, defaultdict, namedtuple, ...
- python基础31[常用模块介绍]
python基础31[常用模块介绍] python除了关键字(keywords)和内置的类型和函数(builtins),更多的功能是通过libraries(即modules)来提供的. 常用的li ...
- Python全栈开发之路 【第六篇】:Python基础之常用模块
本节内容 模块分类: 好处: 标准库: help("modules") 查看所有python自带模块列表 第三方开源模块: 自定义模块: 模块调用: import module f ...
- Python基础之--常用模块
Python 模块 为了实现对程序特定功能的调用和存储,人们将代码封装起来,可以供其他程序调用,可以称之为模块. 如:os 是系统相关的模块:file是文件操作相关的模块:sys是访问python解释 ...
- python基础之常用模块以及格式化输出
模块简介 模块,用一砣代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合.而对于一个复杂的功能来,可能需要 ...
- Day5 - Python基础5 常用模块学习
Python 之路 Day5 - 常用模块学习 本节大纲: 模块介绍 time &datetime模块 random os sys shutil json & picle shel ...
- Python基础5 常用模块学习
本节大纲: 模块介绍 time &datetime模块 random os sys shutil json & picle shelve xml处理 yaml处理 configpars ...
- Python基础之常用模块(二)
一.sys模块 1.sys.exit() 退出程序,这是正常退出程序,与之前用的break不同的是,break只是退出循环,循环之后的代码还会正常运行 2.sys.argv 会返回一个列表,列表中的 ...
- Python基础之常用模块
一.time模块 1.时间表达形式: 在Python中,通常有这三种方式来表示时间:时间戳.元组(struct_time).格式化的时间字符串: 1.1.时间戳(timestamp) :通常来说,时间 ...
随机推荐
- .NET WebSockets 核心原理初体验
上个月我写了<.NET gRPC核心功能初体验>, 里面使用gRPC双向流做了一个打乒乓球的Demo, 实时双向这两个标签是不是很熟悉,对, WebSockets也可以做实时双向通信. 本 ...
- Go-06-数据类型、常量、运算符
数据类型转换 Go语言采用数据类型前置加括号的方式进行类型转换,格式如:T(表达式).T表示要转换的类型:表达式包括变量.数值.函数返回值等. var a int =100 b := float(a) ...
- 网络编程Netty入门:ByteBuf分析
目录 Netty中的ByteBuf优势 NIO使用的ByteBuffer有哪些缺点 ByteBuf的优势和做了哪些增强 ByteBuf操作示例 ByteBuf操作 简单的Demo示例 堆内和堆外内存 ...
- 原创:纯CSS美化单复选框(checkbox、radio)
最重要的一点,隐藏选择框本身.不多说了,上代码: <!doctype html> <html> <head> <meta charset="utf- ...
- 一篇博文让你学会HTML5
HTML 什么是HTML HTML(HyperText Markup Language,超文本标记语言)是用来描述网页的一种语言,它不是一种编程语言,而是一种标记语言. 认识HTML HTML5是构建 ...
- 微信小程序 icon组件详细介绍
这些是提供的所支持的图标样式,根据需求在此基础上去修改大小和颜色. 主要属性: 使用方式: wxml <!--成功图标--> <icon type="success&quo ...
- Python实现Paramiko的二次封装
Paramiko是一个用于执行SSH命令的Python第三方库,使用该库可实现自动化运维的所有任务,如下是一些常用代码的封装方式,多数代码为半成品,只是敲代码时的备份副本防止丢失,仅供参考,目前本人巡 ...
- MS06-040漏洞研究(上)【转载】
课程简介 我在之前的课程中讨论过W32Dasm这款软件中的漏洞分析与利用的方法,由于使用该软件的人群毕竟是小众群体,因此该漏洞的危害相对来说还是比较小的.但是如果漏洞出现在Windows系统中,那么情 ...
- 【python】Leetcode每日一题-二叉搜索迭代器
[python]Leetcode每日一题-二叉搜索迭代器 [题目描述] 实现一个二叉搜索树迭代器类BSTIterator ,表示一个按中序遍历二叉搜索树(BST)的迭代器: BSTIterator(T ...
- 远程连接mysql出现"Can't connect to MySQL server 'Ip' ()"的解决办法
1.大多是防火墙的问题(参考链接:https://blog.csdn.net/jiezhi2013/article/details/50603366) 2.上面方法不能解决,不造成影响情况下可关闭防火 ...