Python6

Python1-环境配置
Python2-基础认识
Python3-数据类型
Python4-面向对象
Python5-闭包和装饰器
Python6-IO模块
Python7-进程线程携程
Python8-网络编程
Python爬虫

time模块

时间戳形式

用于时间间隔计算

import time
print(time.time())

格式化字符串形式

用于展示时间

import time
print(time.strftime('%Y-%m-%d %H:%M:%S %A'))
print(time.strftime('%x %x %A')))
'''
python中时间日期格式化符号:
- %y 两位数的年份表示(00-99)
- %Y 四位数的年份表示(000-9999)
- %m 月份(01-12)
- %d 月内中的一天(0-31)
- %H 24小时制小时数(0-23)
- %I 12小时制小时数(01-12)
- %M 分钟数(00=59)
- %S 秒(00-59)
- %a 本地简化星期名称
- %A 本地完整星期名称
- %b 本地简化的月份名称
- %B 本地完整的月份名称
- %c 本地相应的日期表示和时间表示
- %j 年内的一天(001-366)
- %p 本地A.M.或P.M.的等价符
- %U 一年中的星期数(00-53)星期天为星期的开始
- %w 星期(0-6),星期天为星期的开始
- %W 一年中的星期数(00-53)星期一为星期的开始
- %x 本地相应的日期表示
- %X 本地相应的时间表示
- %Z 当前时区的名称结构化的时间
- %% %号本身
'''

结构化的时间

用于单号获取时间的某一部分

import time
res = time.localtime() # 获取当前结构化时间
print(res)
>>>time.struct_time(tm_year=2022, tm_mon=7, tm_mday=9, tm_hour=17,
tm_min=39, tm_sec=15, tm_wday=5, tm_yday=190, tm_isdst=0)
print(res.tm_year)
>>>2022
print(res.tm_mon)
>>>7
print(res.tm_yday)
>>>190

时间格式转换

import time

'''
时间戳 --time.localtime()/time.gmtime()--> 结构化时间 --time.strftime()--> 格式
化的字符串时间
时间戳 <--time.mktime()-- 结构化时间 <--time.strptime()-- 格式化的字符串时间
'''

print(time.localtime(111111111)) # 时间戳->结构化时间
>>>time.struct_time(tm_year=1973, tm_mon=7, tm_mday=10, tm_hour=8,tm_min=11, tm_sec=51, tm_wday=1, tm_yday=191, tm_isdst=0)

print(time.gmtime(111111111)) # 时间戳->结构化时间(世界标准时间)
>>>time.struct_time(tm_year=1973, tm_mon=7, tm_mday=10, tm_hour=0,tm_min=11, tm_sec=51, tm_wday=1, tm_yday=191, tm_isdst=0)

res = time.localtime(111111111)
print(time.strftime('%Y-%m-%d %X',res)) # 结构化时间->格式化字符串时间
>>>1973-07-10 08:11:51

t = '1983-12-07 01:02:02'
print(time.strptime(t, '%Y-%m-%d %X')) # 格式化字符串时间->结构化时间
>>>time.struct_time(tm_year=1983, tm_mon=12, tm_mday=7, tm_hour=1, tm_min=2,tm_sec=2, tm_wday=2, tm_yday=341, tm_isdst=-1)

res = time.localtime(111111111)
print(time.mktime(res)) # 结构化时间->时间戳

# asctime/ctime无法自定义格式
print(time.asctime()) # 当前结构化时间->格式化字符串时间
>>>Tue Jul 12 20:58:45 2022

res = time.localtime(111111111)
print(time.asctime(res)) # 结构化时间->格式化字符串时间
>>>Tue Jul 10 08:11:51 1973

print(time.ctime(111111111)) # 时间戳->格式化字符串时间
>>>Tue Jul 10 08:11:51 1973

datatime模块

import datetime

res = datetime.datetime.now() # 获取当前时间(返回datetime类对象)
print(res)
>>>2022-07-09 17:20:43.091844

print(res.replace(microsecond=0)) # 去除微秒
>>>2022-07-09 17:20:43

# 时间加减(可选参数:days,seconds,microseconds,milliseconds,minutes,hours,weeks)
new_time = res + datetime.timedelta(days=7)
print(new_time.replace(microsecond=0))
>>>2022-07-16 17:20:43

print(datetime.datetime.utcnow()) # 获取当前世界时间
>>>2022-07-12 13:02:41.486413

print(datetime.datetime.fromtimestamp(111111111)) # 时间戳->固定格式的字符串时间
>>>1973-07-10 08:11:51

print(datetime.datetime.now().date()) # 获取年月日
>>>2022-07-09

print(datetime.datetime.now().time()) # 获取时间
>>>17:20:43.091844

print(datetime.datetime.now().year) # 获取年
>>>2022

print(datetime.datetime.now().month) # 获取月
>>>7

print(datetime.datetime.now().day) # 获取日
>>>9

文件读写

不安全的写法

file = open('a.txt', 'r')
print(file.readlines())  #gbk编码
file.close()

安全写法

上下文管理器

with open("1.txt","w") as f:
    f.write('hello world')

使用类模拟上下文管理器

# 模拟一个open 放在with 上下文管理器中的代码
class My_Open(object):
    # 接收参数,打开的对象,和模式
    def __init__(self,file,mode) -> None:
        self.file = file
        self.mode = mode

    # 这个方法用来对进入上下文文件进行一个初始话的操作
    # 做初始话以外,返回值要返回自己
    def __enter__(self):
        self.file_handle = open(self.file,self.mode)
        return self.file_handle
  
    # 这个方法用来在退出上下文环境进行一个资源回收操作
    def __exit__(self,exc_type,exc_val,exc_tb):
        # 异常接收:exc_type异常类型,exc_val异常值,exc_tb回溯信息
        self.file_handle.close()
        # 该函数默认值为False
        return True


    def show(self):
        print()

with My_Open('b.txt','w') as f:
    f.write('bbbb')

文件常用的打开模式

  1. r 以读的模式打开文件
  2. w 以写的模式打开文件,如果文件不存在则创建文件,覆盖
  3. a 以追加的模式打开文件,如果文件不存在则创建,追加
  4. b 以二进制的方式打开文件,不能单独使用多为‘rb,wb’
  5. + 以读写的模式打开文件,不能单独使用多为‘a+’
file = open('b.txt', 'w')
file.write('Python')  #gbk编码
file.close()

file = open('b.txt', 'a')
file.write('Python')  #gbk编码
file.close()

src_file = open('logo.png','rb')
target_file = open('copylogo.png','wb')
target_file.write(src_file.read())
target_file.close()
src_file.close()

文件对象常用的方法

  1. read([size])

    从文件中读取size个字节或字符的内容返回,若省略[size],则读取到文件末尾

  2. readline()

    从文件中读取一行的内容

  3. readliness()

    把文本文件中每一行都作为独立的字符串对象,并将这些对象放入列表返回

  4. write(str)

    将字符串str内容写入文件

  5. writelines(s_list)

    将字符串列表s_list写入文本文件,不添加换行符

  6. seek(offset)

    把文件的指针移动到新的位置

  7. tell()

    返回文件指针的当前位置

  8. flush()

    把缓冲区内容写入文件,但不关闭文件

  9. close()

    把缓冲区内容写入文件,但不关闭文件,关闭文件释放资源

file = open('a.txt','r')
# print(file.read())
# print('.')
# print(file.readline(4))
# print('.')
print(file.readlines())
file.close()

file = open('c.txt','a')
file.write('hallo')
lst = ['Java','go','python']
file.writelines(lst)
file.close()

file = open('a.txt','r')
file.seek(2)  # 一个汉子两个字节
print(file.read())
print(file.tell())
file.close()

file = open('d.txt','a')
file.write('hello')
file.flush()        # 打开同道执行程序后不关闭,可继续使用
file.write('world')
file.close()        # 打开通道执行程序后关闭,不可继续使用

表格处理

xlrd / xlwt

import xlrd
import xlwt

location = r'C:\Users\32628\Desktop\tct.xls'
data = xlrd.open_workbook(location)
table = data.sheets()[0]
  
nrows = table.nrows  # 行
for i in range(nrows):
    if i == 0 :
        continue
    tc_list = table.row_values(i)  

数据库操作

pymysql

在学习过程中使用较多,有称为学者库

python -m pip install pymysql

使用的是mysql的事务环境进行操作

py对应sql语句中的事务自动提交有cur.autocommit(True)方法

但是要使用connect_db.begin()方法进行手动开启事务

from pymysql import *
conn = connect(host='地址',user='账号',password='密码',
               database='库名',port=端口号,charset='utf8')
# 查寻操作
try:
    cur = conn.cursor()  # 创建游标对象,可以利用对象进行数据库的操作
    cur.execute('select * from office')  # 执行数据库语句
    result = cur.fetchall()  # 返回5数据
    for item in result:
        print('学号{0} 姓名{1} 班级{2}'.format(item[0],item[1],item[2]))
    print(result)
    print('sucess')  # 测试是否连接成功,如果连接成功输出sucess

except Exception as ex:
    print(ex)
finally:  # 异常处理
    cur.close()  # 关闭创建的游标
    conn.close()  # 关闭连接的数据库

# 指定关键字查询
try:
    cur = conn.cursor()  # 创建游标对象,可以利用对象进行数据库的操作
    cur.execute('select * from office where userid=%s',[194643060])  # 执行数据库语句
    result = cur.fetchall()  # 返回数据
    for item in result:
        print('学号{0} 姓名{1} 班级{2}'.format(item[0],item[1],item[2]))
    print(result)
    print('sucess')  # 测试是否连接成功,如果连接成功输出sucess

except Exception as ex:
    print(ex)
finally:  # 异常处理
    cur.close()  # 关闭创建的游标
    conn.close()  # 关闭连接的数据库

# 添加操作
try:
    cur = conn.cursor()
    insersql = "insert into office(userid,username,userclass) values (%s,%s,%s)"
    cur.execute(insersql,(1946430,'张三','信息安全',))
    conn.commit()  # 提交sql语句
    print('sucess')
except Exception as ex:
    print(ex)
finally:  # 异常处理
    cur.close()  # 关闭创建的游标
    conn.close()  # 关闭连接的数据库

sqlalchemy

项目中使用较多

python -m pip install sqlalchemy
from sqlalchemy import Column, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

# 创建对象的基类
Base = declarative_base()

# 初始化数据库链接
engine = create_engine(
    'mysql+mysqldb://root:toor@127.0.0.1:3306/test')

# 定义User对象
class User(Base):
    # 表的名字
    __tablename__ = 't_student'

    # 表的结构
    id = Column(Integer, primary_key=True, autoincrement=True)
    displayName = Column(String(20), nullable=True)
    userName = Column(String(64), nullable=False, index=True)
    passWord = Column(String(64), nullable=False)
    auth = Column(String(200), nullable=False)
    userId = Column(String(64), nullable=True)
    schoolId = Column(String(64), nullable=True)
    schoolName = Column(String(20), nullable=True)
    token = Column(String(64), nullable=True)
    newToken = Column(String(64), nullable=True)

    def __init__(self, id, displayName, userName, passWord, auth, userId, schoolId, schoolName, token, newToken):
        self.id = id
        self.displayName = displayName
        self.userName = userName
        self.passWord = passWord
        self.auth = auth
        self.userId = userId
        self.schoolId = schoolId
        self.schoolName = schoolName
        self.token = token
        self.newToken = newToken

# 创建DBSession类型,绑定引擎
DBSession = sessionmaker(bind=engine)

# 创建session对象,实例化对象
session = DBSession()

# 增加数据
new_user = User(id=1, displayName='张三', userName='zhangsan', passWord='123456', auth='1', userId='194643060', schoolId='1', schoolName='信息安全', token='1', newToken='1')
session.add(new_user)

# 提交即保存到数据库
session.commit()
session.close()

# 增加多个数据
user1 = User(id=2, displayName='李四', userName='lisi', passWord='123456', auth='1', userId='194643061', schoolId='1', schoolName='信息安全', token='1', newToken='1')
user2 = User(id=3, displayName='王五', userName='wangwu', passWord='123456', auth='1', userId='194643062', schoolId='1', schoolName='信息安全', token='1', newToken='1')
user3 = User(id=4, displayName='赵六', userName='zhaoliu', passWord='123456', auth='1', userId='194643063', schoolId='1', schoolName='信息安全', token='1', newToken='1')
session.add_all([user1, user2, user3])
# 提交即保存到数据库
session.commit()
session.close()

# 查询全部
query_obj = session.query(User).all()
for obj in query_obj:
    print(obj.id, obj.name, obj.age, obj.sex, obj.phone)

# 查询指定条件
query_obj = session.query(User).filter_by(name='张三').all()
for obj in query_obj:
    print(obj.id, obj.name, obj.age, obj.sex, obj.phone)

# 查询指定条件
query_obj = session.query(User).filter(User.auth.contains('1')).all()
for obj in query_obj:
    print(obj.id, obj.name, obj.age, obj.sex, obj.phone)

# 查询指定条件
query_obj = session.query(User).filter(User.schoolName == '信息安全').first().all()
for obj in query_obj:
    print(obj.id, obj.name, obj.age, obj.sex, obj.phone)

# 删除
user_willdel = session.query(User).filter_by(User.name.isnot(None)).first()

# 提交即保存到数据库
session.delete(user_willdel)
session.commit()
session.close()

# 修改数据
user_willupdate = session.query(User).filter_by(User.id == 1).first()
user_willupdate.name = '王大锤'
session.commit()
session.close()

redis

主从

# encoding=utf-8
# 导入redis库
import redis

def dbnosql():
    # 创建redis的连接实例
    try:
        # db=0为操作的是0号数据库
        rs = redis.Redis(host='192.168.186.132',port=6379,db=0)
    except Exception as e:
        print(e)

    # 添加
    result = rs.set('name','itcast')
    print(result)
  
    # 获取
    name =rs.get('name')
    print(name)

if __name__ == '__main__':
    dbnosql()

redis-py-cluster集群

# encoding=utf-8
# 导入redis-py-cluster库
from rediscluster import RedisCluster

def dbnosql():
    # 创建redis的连接实例
    nodes = [{'host':'192.168.186.132','post':'6379'},{'host':'192.168.186.132','post':'6380'},]
    try:
        rc = RedisCluster(startup_nodes = nodes,decode_responses=True)
        rc.set('age',15)
    except Exception as e:
        print(e)

if __name__ == '__main__':
    dbnosql()

os模块

os.getcwd() # 获取当前工作目录
os.chdir("dirname") # 改变当前脚本工作目录;相当于终端里面的cd命令
os.listdir('dirname') # 获取指定目录下的所有文件和文件夹,包括隐藏文件,并返回列表
os.mkdir('dirname') # 创建文件夹;相当于终端里面的mkdir dirname
os.makedirs('dirname1/dirname2') # 递归创建多层目录
os.remove() # 删除一个文件
os.rmdir('dirname') # 删除单级空目录,若目录不为空则无法删除,则报错
os.rename('oldname','newname') # 重命名文件/目录
os.system("rm -rf /") # 运行终端命令
os.environ # 获取系统环境变量
os.environ.get('KEY') # 获取系统环境变量的某一个值
os.getenv('KEY') # 获取系统环境变量的某一个值
os.stat('path/filename')# 获取文件/目录信息
os.name # 输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
os.path.split(path) # 将path分割成目录和文件名,返回元组
os.path.dirname(path) # 返回path的父级目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path) # 返回path最后的文件名。如path以/或\结尾,那么就会返回空值。即
os.path.split(path)的第二个元素
os.path.exists(path) # 如果path存在,返回True;如果path不存在,返回False
os.path.isabs(path) # 如果path是绝对路径,返回True
os.path.isfile(path) # 如果path是一个存在的文件,返回True。否则返回False
os.path.isdir(path) # 如果path是一个存在的目录,则返回True。否则返回False
os.path.join(path1[, path2[, ...]]) # 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
os.path.getatime(path) # 返回path所指向的文件或者目录的最后读取时间
os.path.getmtime(path) # 返回path所指向的文件或者目录的最后修改时间
os.path.getctime(path) # # 返回path所指向的文件或者目录的创建时间(windows平台中)
os.path.getsize(path) # 返回path的大小

一键安装常用库

import os 
libs = {"numpy", "matplotlib", "pillow", "sklearn", "requests",
        "jieba", "beautifulsoup4", "whee1", "networkx", "sympy",
        "pyinstaller", "django", "flask", "werobot", "pyqt5",
        "pandas", "pyopengl", "pypdf2", "docopt", "pygame"}
try:
    for lib in libs:
        os.system("pip install" + lib)
    print("Successful")
except:
    print("Failed Somehow")

查询当前存在的主机

import os  # 导入os模块,可以执行一些dos命令和linux命令
from concurrent.futures import ThreadPoolExecutor  # 导入多线程


def gao(ip):
    output = os.popen(f"ping -n 1 {ip}").readlines()  # 将传入的IP拼接成dos命令
    for i in range(66000):  # 计数
        print(i)
    for w in output:  # 判断ping命令返回的数据
        # print(w)
        if str(w).upper().find('TTL') >= 0:  # 如果返回的有TTL字样且值大于等于0
                    print(ip, 'ok')


if __name__ == "__main__":    # 程序开始
    with ThreadPoolExecutor(50) as t:  # 创建线程池,使用上下文管理区的写法
        for i in range(1,255):  
            for it in range(1,255):
                a = t.submit(gao,f"10.9.{i}.{it}")  # 启用多线程,运行gao函数
from scapy.all import * 
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
net="10.9.47."
# 此处修改目标网段
for host in range(1,255):
    ip=f"{net}{host}"
    # print(f"[-]Tring ip {ip}")
    # 解除上一行注释即可看到探查过程,但是结果会被分散
    pkt=IP(src="10.4.7.138",dst=f"{ip}")/ICMP()
    # 此处src的内容为源ip
    res=sr1(pkt,timeout = 0.2, verbose = False)
    if res:
        print(f"[+]Alive {ip}")

configparser模块

配置文件test.ini

# 这是注释
; 这也是注释
[default]
delay = 10
compression = true
compression_Level = 2
language_code = en-us
time_zone = UTC
salary = 3.5

[db]
db_type : mysql
database_name = catalogue_data
user = root
password = root
host = 127.0.0.1
port = 3306
charset = utf8

import configparser
config = configparser.ConfigParser()
config.read('data/test.ini', encoding='utf-8')

#查看所有的标题
sections = config.sections()
print(sections)
>>>['default', 'db']

#查看标题default下所有key=value的key
options = config.options('default')
print(options)
>>>['delay', 'compression', 'compression_level', 'language_code', 'time_zone',
'salary']

#查看标题default下所有key=value的(key,value)格式
li = config.items('default')
print(li)
>>>[('delay', '10'), ('compression', 'true'), ('compression_level', '2'),
('language_code', 'en-us'), ('time_zone', 'UTC'), ('salary', '3.5')]

#查看标题default下delay的值=>字符串格式
val = config.get('default', 'delay')
print(val)
>>>10

#查看标题default下delay的值=>整数格式
int_val = config.getint('default','delay')
print(int_val)
>>>10

#查看标题default下salary的值=>浮点型格式
float_val = config.getfloat('default','salary')
print(float_val)
>>>3.5

#查看标题default下compression的值=>布尔值格式
bool_val = config.getboolean('default','compression')
print(bool_val)
>>>True

import configparser
config=configparser.ConfigParser()
config.read('data/test.ini', encoding='utf-8')

#删除整个标题default(包括下面的配置项)
config.remove_section('default')

#删除标题default下的compression和delay
config.remove_option('default', 'compression')
config.remove_option('default', 'delay')

#判断是否存在某个标题
print(config.has_section('default'))

#判断标题default下是否有delay
print(config.has_option('default', 'delay'))

#添加一个section
config.add_section('connect')

#在标题connect下添加thread=10的配置(如果没有此配置,则会创建配置项,如果已有此配置,则修改原配置项)
config.set('connect', 'thread', '10')
config.set('connect', 'thread', 10) # 这样写回报错,必须写字符串格式

#最后将修改的内容写入文件,完成最终的修改
config.write(open('test.ini', 'w'))

import configparser
config = configparser.ConfigParser()
config["default"] = {'delay': '15',
        'compression': 'false',
        'compression_Level': '3'}

config['db'] = {}
config['db']['User'] = 'root'
config['db2'] = {}
topsecret = config['db2']
topsecret['port'] = '3306'
topsecret['compression'] = 'true'
config['default']['compression'] = 'true'
with open('data/test.ini', 'w') as f:
    config.write(f)
posted @ 2025-03-26 10:59  *--_-  阅读(47)  评论(0)    收藏  举报