日志模块

import logging

import logging

#默认级别为warning,默认打印到终端
logging.debug('debug') #
logging.info('info') #
logging.warning('warn') #
logging.error('error') #
logging.critical('critical')#
可在logging.basicConfig()函数中通过具体参数来更改logging模块默认行为,可用参数有
filename:用指定的文件名创建FiledHandler(后边会具体讲解handler的概念),这样日志会被存储在指定的文件中。
filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
format:指定handler使用的日志显示格式。
datefmt:指定日期时间格式。
level:设置rootlogger(后边会讲解具体概念)的日志级别
stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。 #格式
%(name)s:Logger的名字,并非用户名,详细查看 %(levelno)s:数字形式的日志级别 %(levelname)s:文本形式的日志级别 %(pathname)s:调用日志输出函数的模块的完整路径名,可能没有 %(filename)s:调用日志输出函数的模块的文件名 %(module)s:调用日志输出函数的模块名 %(funcName)s:调用日志输出函数的函数名 %(lineno)d:调用日志输出函数的语句所在的代码行 %(created)f:当前时间,用UNIX标准的表示时间的浮 点数表示 %(relativeCreated)d:输出日志信息时的,自Logger创建以 来的毫秒数 %(asctime)s:字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒 %(thread)d:线程ID。可能没有 %(threadName)s:线程名。可能没有 %(process)d:进程ID。可能没有 %(message)s:用户输出的消息

logging.basicConfig详细解释

logging.basicConfig(filename='access.log',
format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',
level=10)
import logging
#介绍
#logging模块的Formatter,Handler,Logger,Filter对象
#Logger:产生日志的对象
logger1=logging.getLogger('访问日志')
#Filter:过滤日志的对象
#Handler:接收日志然后控制打印到不同的地方,FileHandler用来打印到文件中,#StreamHandler用来打印到终端
h1=logging.StreamHandler()
h2=logging.FileHandler('access.log',encoding='utf-8')
#Formatter对象:可以定制不同的日志格式对象,然后绑定给不同的Handler对象使用,以此来控制不同的Handler的日志格式
formatter1=logging.Formatter(
fmt='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',) #使用
#logger负责产生日志,交给Filter过滤,然后交给不同的Handler输出,handler需要绑定日志格式
h1.setFormatter(formatter1)
h2.setFormatter(formatter1)
logger1.addHandler(h1)
logger1.addHandler(h2)
logger1.setLevel(10)
h1.setLevel(20) #Handler的日志级别设置应该高于Logger设置的日志级别
logger1.debug('debug')
logger1.info('info')
logger1.warning('warning')
logger1.error('error')
logger1.critical('critical')

logging模块的Formatter,Handler,Logger,Filter对象

#应用
import os
import logging.config # 定义三种日志输出格式 开始 standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
'[%(levelname)s][%(message)s]' #其中name为getlogger指定的名字 simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s' id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s' # 定义日志输出格式 结束 logfile_dir = os.path.dirname(os.path.abspath(__file__)) # log文件的目录 logfile_name = 'all2.log' # log文件名 # 如果不存在定义的日志目录就创建一个
if not os.path.isdir(logfile_dir):
os.mkdir(logfile_dir) # log文件的全路径
logfile_path = os.path.join(logfile_dir, logfile_name) # log配置字典
LOGGING_DIC = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': standard_format
},
'simple': {
'format': simple_format
},
},
'filters': {},
'handlers': {
#打印到终端的日志
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler', # 打印到屏幕
'formatter': 'simple'
},
#打印到文件的日志,收集info及以上的日志
'default': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件
'formatter': 'standard',
'filename': logfile_path, # 日志文件
'maxBytes': 1024*1024*5, # 日志大小 5M
'backupCount': 5,
'encoding': 'utf-8', # 日志文件的编码,再也不用担心中文log乱码了
},
},
'loggers': {
#logging.getLogger(__name__)拿到的logger配置
'': {
'handlers': ['default', 'console'], # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
'level': 'DEBUG',
'propagate': True, # 向上(更高level的logger)传递
},
},
} def load_my_logging_cfg():
logging.config.dictConfig(LOGGING_DIC) # 导入上面定义的logging配置
logger = logging.getLogger(__name__) # 生成一个log实例
logger.info('It works!') # 记录该文件的运行状态 if __name__ == '__main__':
load_my_logging_cfg()

logging配置文件

正则模块

import re

  正则就是用一些具有特殊含义的符号组合到一起(称为正则表达式)来描述字符或者字符串的方法

# re模块的方法
print(re.findall('a[-+/*]b','axb azb aAb a+b a-b'))
# re.search()
print(re.search('a[-+/*]b','axb azb aAb a+b a-b')) #有结果返回一个对象,无结果返回None
print(re.search('a[-+/*]b','axb azb aAb a+b a-b').group()) #group()方法只匹配成功一次就返回
#re.match()
print(re.match('a[-+/*]b','axb azb aAb a+b a-b')) #从头开始取,无结果返回None
print(re.match('a[-+/*]b','a*b azb aAb a+b a-b').group())
#re.split()
print(re.split(':','root:x:0:0::/root',maxsplit=1))
#re.sub()
print(re.sub('root','admin','root:x:0:0::/root',1))
print(re.sub('^([a-z]+)([^a-z]+)(.*?)([^a-z]+)([a-z]+)$',r'\5\2\3\4\1','root:x:0:0::/bash'))
#re.compile()
obj=re.compile('a\d{2}b')
print(obj.findall('a12b a123b a124a a82b'))
print(obj.search('a12b a123b a124a a82b'))
# \w 匹配字母数字及下划线
print(re.findall('\w','lary 123 + _ - *'))
# \W 匹配非字母数字及下划线
print(re.findall('\W','lary 123 + _ - *'))
# \s 匹配任意空白字符
print(re.findall('\s','lary\tn 123\n3 + _ - *'))
# \S 匹配任意非空字符
print(re.findall('\S','lary\tn 123\n3 + _ - *'))
# \d 匹配任意数
print(re.findall('\d','lary\tn 123\n3 + _ - *'))
# \D 匹配任意非数字
print(re.findall('\D','lary\tn 123\n3 + _ - *'))
# \n 匹配一个换行符
print(re.findall('\n','lary\tn 123\n3 + _ - *'))
# \t 匹配一个制表符
print(re.findall('\t','lary\tn 123\n3 + _ - *'))
# ^ 匹配字符串开头
print(re.findall('^e','elary\tn 123\n3 ego + _ - *'))
# $ 匹配字符串的末尾
print(re.findall('o$','elary\tn 123\n3 ego + _ - *o'))
# . 匹配任意一个字符(除了换行符)
print(re.findall('a.b','a1b a b a-b aaaab'))
# ? 匹配0个或1个由前面的正则表达式定义的片段,非贪婪方式
print(re.findall('ab?','a ab abb abbb a1b'))
# * 匹配0个或多个的表达式
print(re.findall('ab*','a ab abb abbb a1b'))
# + 匹配1个或多个的表达式
print(re.findall('ab+','a ab abb abbb a1b'))
# {n,m}匹配n到m次由前面的正则表达式定义的片段,贪婪方式
print(re.findall('ab{0,1}','a ab abb abbb a1b'))
print(re.findall('ab?','a ab abb abbb a1b'))
print(re.findall('ab{2,3}','a ab abb abbb a1b'))
#.*?匹配任意个字符,非贪婪方式
print(re.findall('a.*?b','a123b456b'))
#.* 匹配任意个字符,贪婪方式
print(re.findall('a.*b','a123b456b'))
# a|b 匹配a或b
print(re.findall('compan(ies|y)','too many companies shut down,and the next is my company'))
print(re.findall('compan(?:ies|y)','too many companies shut down,and the next is my company'))
# [...] 表示一组字符,取括号中任意一个字符
print(re.findall('a[a-z]b','axb azb aAb a+b a-b'))
print(re.findall('a[a-zA-Z]b','axb azb aAb a+b a-b'))
print(re.findall('a[-+/*]b','axb azb aAb a+b a-b')) #-应该写在[]中的两边
# [^...]不在[]中的字符
print(re.findall('a[^-+/*]b','axb azb aAb a+b a-b'))
# (n)精确匹配n个前面表达式
# () 匹配括号内的表示式,也表示一个组
# \A 匹配字符串开始
# \Z 匹配字符串结束,如果存在换行,只匹配到换行前的结束字符串
# \z 匹配字符串结束
# \G 匹配最后匹配完成的位置 print(re.findall(r'a\\c','a\c alc aBc')) #r''代表原生表达式

正则表达式

time模块

import time

import time

print(time.time())      #时间戳
print(time.localtime()) #本地时区时间
print(time.gmtime()) #标准时间
print(time.strftime("%Y-%m-%d %X")) #格式化时间 import datetime print(datetime.datetime.now())
print(datetime.datetime.fromtimestamp(11111))
print(datetime.datetime.now()+datetime.timedelta(days=3))
print(datetime.datetime.now().replace(year=1999))

  

1 #--------------------------按图1转换时间
2 # localtime([secs])
3 # 将一个时间戳转换为当前时区的struct_time。secs参数未提供,则以当前时间为准。
4 time.localtime()
5 time.localtime(1473525444.037215)
6
7 # gmtime([secs]) 和localtime()方法类似,gmtime()方法是将一个时间戳转换为UTC时区(0时区)的struct_time。
8
9 # mktime(t) : 将一个struct_time转化为时间戳。
10 print(time.mktime(time.localtime()))#1473525749.0
11
12
13 # strftime(format[, t]) : 把一个代表时间的元组或者struct_time(如由time.localtime()和
14 # time.gmtime()返回)转化为格式化的时间字符串。如果t未指定,将传入time.localtime()。如果元组中任何一个
15 # 元素越界,ValueError的错误将会被抛出。
16 print(time.strftime("%Y-%m-%d %X", time.localtime()))#2016-09-11 00:49:56
17
18 # time.strptime(string[, format])
19 # 把一个格式化时间字符串转化为struct_time。实际上它和strftime()是逆操作。
20 print(time.strptime('2011-05-05 16:37:06', '%Y-%m-%d %X'))
21 #time.struct_time(tm_year=2011, tm_mon=5, tm_mday=5, tm_hour=16, tm_min=37, tm_sec=6,
22 # tm_wday=3, tm_yday=125, tm_isdst=-1)
23 #在这个函数中,format默认为:"%a %b %d %H:%M:%S %Y"。

1 #--------------------------按图2转换时间
2 # asctime([t]) : 把一个表示时间的元组或者struct_time表示为这种形式:'Sun Jun 20 23:21:05 1993'。
3 # 如果没有参数,将会将time.localtime()作为参数传入。
4 print(time.asctime())#Sun Sep 11 00:43:43 2016
5
6 # ctime([secs]) : 把一个时间戳(按秒计算的浮点数)转化为time.asctime()的形式。如果参数未给或者为
7 # None的时候,将会默认time.time()为参数。它的作用相当于time.asctime(time.localtime(secs))。
8 print(time.ctime()) # Sun Sep 11 00:46:38 2016
9 print(time.ctime(time.time())) # Sun Sep 11 00:46:38 2016

random模块

import random

import random

print(random.random())          #大于0小于1之间的小数
print(random.randint(1,3)) #大于1且小于等于3之间的整数(包括头尾)
print(random.randrange(1,3)) #大于1且小于等于3之间的整数(顾头不顾尾)
print(random.choice([1,'hell',3])) #取其中一个
print(random.sample([1,2,3],2)) #取任意两个组合
print(random.uniform(1,4)) #取1-4之间的小数 l=[1,2,3,4,5]
random.shuffle(l) #打乱原来的顺序
print(l)
#随机验证码小功能
def make_code(n):
res=''
for i in range(n):
s1=str(random.randint(0,9))
s2=chr(random.randint(65,90))
res+=random.choice([s1,s2])
return res res=make_code(6)
print(res)

os模块

import os

os.path.abspath(path)  #返回path规范化的绝对路径
os.path.dirname(path) #返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.exists(path) #如果path存在,返回True;如果path不存在,返回False
os.path.join(path1[, path2[, ...]]) #将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
os.getcwd() #获取当前工作目录,即当前python脚本工作的目录路径
os.chdir("dirname") #改变当前脚本工作目录;相当于shell下cd
os.curdir #返回当前目录: ('.')
os.pardir #获取当前目录的父目录字符串名:('..')
os.makedirs('dirname1/dirname2') #可生成多层递归目录
os.removedirs('dirname1') #若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir('dirname') #生成单级目录;相当于shell中mkdir dirname
os.rmdir('dirname') #删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
os.listdir('dirname') #列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.remove() #删除一个文件
os.rename("oldname","newname") #重命名文件/目录
os.stat('path/filename') #获取文件/目录信息
os.sep #输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
os.linesep #输出当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"
os.pathsep #输出用于分割文件路径的字符串 win下为;,Linux下为:
os.name #输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
os.system("bash command") #运行shell命令,直接显示
os.environ #获取系统环境变量
os.path.split(path) #将path分割成目录和文件名二元组返回
os.path.basename(path) #返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.isabs(path) #如果path是绝对路径,返回True
os.path.isfile(path) #如果path是一个存在的文件,返回True。否则返回False
os.path.isdir(path) #如果path是一个存在的目录,则返回True。否则返回False
os.path.getatime(path) #返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path) #返回path所指向的文件或者目录的最后修改时间
os.path.getsize(path) #返回path的大小
#在Linux和Mac平台上,该函数会原样返回path,在windows平台上会将路径中所有字符转换为小写,并将所有斜杠转换为反斜杠。
print(os.path.normcase('c:/windows\\system32\\'))
#规范化路径,如..和 /
print(os.path.normpath('c://windows\\System32\\../Temp/'))
a = '/Users/jieli/test1/\\\a1/\\\\aa.py/../..'
print(os.path.normpath(a))
#os路径处理
#方式一:
import os,sys
Base_dir = os.path.normpath(os.path.join(
os.path.abspath(__file__),
os.pardir, #上一级
os.pardir,
os.pardir
))
print(Base_dir) #方式二:
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

sys模块

import sys

import sys

sys.argv        #命令行参数List,第一个元素是程序本身路径
sys.exit(n) #退出程序,正常退出时exit(0)
sys.version #获取Python解释程序的版本信息
sys.maxint #最大的Int值
sys.path #返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform #返回操作系统平台名称
def process(percent,width=50):
if percent >=1:
percent=1
show_str=('[%%-%ds]'%width)%('+'*int(width*percent))
print('\r%s %d%%'%(show_str,percent*100),end='') recv_size=0
total_size=10241
while recv_size < total_size:
time.sleep(0.1)
recv_size+=1024
process(recv_size/total_size)

打印进度条

shutil模块

import shutil

shutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w')) #将文件内容拷贝到另一个文件中
shutil.copyfile('f1.log', 'f2.log') #拷贝文件,目标文件无需存在
shutil.copymode('f1.log', 'f2.log') #仅拷贝权限。内容、组、用户均不变,目标文件必须存在
shutil.copystat('f1.log', 'f2.log') #仅拷贝状态的信息,包括:mode bits, atime, mtime, flags,目标文件必须存在
shutil.copy('f1.log', 'f2.log') #拷贝文件和权限
shutil.copy2('f1.log', 'f2.log') #拷贝文件和状态信息
#递归的去拷贝文件夹,目标目录不能存在,注意对folder2目录父级目录要有可写权限,ignore的意思是排除
shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))
shutil.rmtree('folder1') #递归的去删除文件
shutil.move('folder1', 'folder3') #递归的去移动文件
shutil.make_archive("data_bak", 'gztar', root_dir='/data') #将 /data 下的文件打包放置当前程序目录
shutil.make_archive("/tmp/data_bak", 'gztar', root_dir='/data') #将 /data下的文件打包放置 /tmp/目录

json&pickle模块

import json

import pickle

  序列化:我们把对象(变量)从内存中变成可存储或传输的过程称之为序列化

  序列化的目的:在断电或重启程序之前将程序当前内存中所有数据都保存下来,以便于下次程序执行能够从文件中载入之前的数据;序列化之后,不仅可以把序列化后的内容写入磁盘,还可以通过网络传输到别的机器上,如果收发的双方约定好实用一种序列化的格式,那么便打破了平台/语言差异化带来的限制,实现了跨平台数据交互

  序列化之json

  json表示的对象就是标准的JaveScripts语言的对象,可以被所有语言读取,也可以方便的存储到磁盘或者通过网络传输,json和python内置的数据类型对应如下:

json类型 python类型
{} dict
[] list
"String" str
1234.57 int或float
true/false True/False
null None
dic={'a':1}
res=json.dumps(dic)
print(res,type(res)) #{"a": 1} <class 'str'> x=None
res=json.dumps(x)
print(res,type(res)) #null <class 'str'> #序列化:json.dumps和json.dump用法
user = {"name":'lary','age':18}
with open('user.json','w',encoding='utf-8') as f:
f.write(json.dumps(user)) #json.dumps把单引号变为双引号 user = {"name": 'lary', 'age': 16}
json.dump(user,open('user.json','w',encoding='utf-8')) #反序列化:json.loads和json.load的用法
with open('user.json','r',encoding='utf-8') as f:
data=json.loads(f.read())
print(data) data=json.load(open('user.json','r',encoding='utf-8'))
print(data)

  序列化之pickle

  pickle只能用于python,可以识别python所有的数据类型,但是可能不同版本的python彼此都不兼容

#序列化:pickle.dumps和pickle.dump,序列化后的数据类型为bytes类型
s={1,2,3,4,5} with open('user.pkl','wb',) as f:
f.write(pickle.dumps(s)) pickle.dump(s, open('user.pkl', 'wb')) #反序列化:pickle.loads和pickle.load
with open('user.pkl','rb') as f:
data=pickle.loads(f.read())
print(data) data=pickle.load(open('user.pkl','rb'))
print(data)

shelve模块

import shelve

   shelve模块比pickle模块简单,只有一个open函数,返回类似字典的对象,可读可写;key必须为字符串,而值可以是python所支持的数据类型

f=shelve.open('db.sh1')
#存数据
f['student1']={'name':'lary',"age":18}
#取数据
print(f['student1'])
f.close()

xml模块

  xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单

<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank updated="yes">69</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>

xml数据

  xml协议在各个语言里的都 是支持的,在python中可以用以下模块操作xml

from xml.etree import ElementTree

tree=ElementTree.parse('a.xml')

root=tree.getroot()
print(root.tag,root.attrib,root.text) #三种查找方式
#从子节点查找
print(root.find('country'))
print(root.findall('country'))
#从树形结构中查找
print(list(root.iter('rank'))) for country in root.findall('country'):
rank=country.find('rank')
print(rank.tag,rank.attrib,rank.text) #遍历文档树
for item in root:
#print('=====>',item.attrib['name'])
for i in item:
print(i.tag,i.attrib,i.text) #修改文档
for year in root.iter('year'):
#print(year.tag,year.attrib,year.text)
year.set('updated','yes')
year.text=str(int(year.text)+1) tree.write('a.xml') #添加节点
for country in root:
obj=ElementTree.Element('egon')
obj.attrib={"name":'egon',"age":''}
obj.text='egon is good'
country.append(obj)

configparser模块

[section1]
k1 = v1
k2:v2
user=egon
age=18
is_admin=true
salary=31 [section2]
k1 = v1

ConfigureFile

  在python中可以用以下模块操作xml

import configparser

config=configparser.ConfigParser()
config.read('my.ini') #查看
#查看所有的标题
res=config.sections()
print(res) #查看标题section下所有key=value的key
options=config.options('section1')
print(options) #查看标题section下所有key=value的(key,value)形式
item=config.items('section1')
print(item) #查看标题section1下user的值=>字符串格式
val=config.get('section1','user')
print(val) #查看标题section1下age的值=>整数格式
val1=config.getint('section1','age')
print(val1) #查看标题section1下is_admin的值=>布尔值格式
val2=config.getboolean('section1','is_admin')
print(val2) #查看标题section1下salary的值=>浮点型格式
val3=config.getfloat('section1','salary')
print(val3) #修改
#删除整个标题section2
config.remove_section('section2') #删除标题section1下的某个k1和k2
config.remove_option('section1','k1')
config.remove_option('section1','k2') #判断是否存在某个标题
print(config.has_section('section1')) #判断标题section1下是否有user
print(config.has_option('section1','')) #添加一个标题
config.add_section('lary') #在标题egon下添加name=lary,age=18的配置
config.set('lary','name','lary')
config.set('lary','age','') #必须是字符串 #最后将修改的内容写入文件,完成最终的修改
config.write(open('a.cfg','w'))

hashlib模块

  hash:一种算法,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法。特点是内容相同则hash运算结果相同,内容稍微改变则hash值则变;不可逆推;无论校验多长的数据,得到的哈希值长度固定

import hashlib

m=hashlib.md5()

m.update('lary123'.encode('utf-8'))
print(m.hexdigest()) #对加密算法中添加自定义key再来做加密
hash=hashlib.sha256('898sadfd'.encode('utf-8'))
hash.update('hello'.encode('utf-8'))
print(hash.hexdigest()) #hmac模块,它内部对我们创建key和内容进行进一步的处理然后再加密
import hmac h=hmac.new('good'.encode('utf-8'))
h.update('hello'.encode('utf-8'))
print(h.hexdigest())
#模拟撞库破解密码
pwd={
"lary",
"lary123",
"lary321"
}
def make_pwd_dic(pwd):
dic={}
for p in pwd:
m=hashlib.md5()
m.update(p.encode('utf-8'))
dic[p]=m.hexdigest()
return dic def break_code(code,pwd_dic):
for k,v in pwd_dic.items():
if v==code:
print("密码是%s"%k) code='3043b3256c1c64338167b7b1d71d0c14'
break_code(code,make_pwd_dic(pwd))

撞库模拟

subprocess模块

import subprocess
import time subprocess.Popen('tasklist',shell=True)
print('===主')
time.sleep(1) obj1=subprocess.Popen('tasklist',shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
) obj2=subprocess.Popen('findstr python',shell=True,
stdin=obj1.stdout,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
) print(obj2.stdout.read().decode('gbk'))

第八章 Python之常用模块的更多相关文章

  1. python的常用模块之collections模块

    python的常用模块之collections模块 python全栈开发,模块,collections 认识模块 什么是模块?    常见的场景:一个模块就是一个包含了python定义和声明的文件,文 ...

  2. python之常用模块

    python 常用模块 之 (subprocess模块.logging模块.re模块) python 常用模块 之 (序列化模块.XML模块.configparse模块.hashlib模块) pyth ...

  3. python之常用模块二(hashlib logging configparser)

    摘要:hashlib ***** logging ***** configparser * 一.hashlib模块 Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等. 摘要算法 ...

  4. Python学习——python的常用模块

    模块:用一堆代码实现了某个功能的代码集合,模块是不带 .py 扩展的另外一个 Python 文件的文件名. 一.time & datetime模块 import time import dat ...

  5. python 之常用模块

    一 认识模块 二 常用模块    (1)re模块    (2)collections模块 一  认识模块     (1)什么是模块      (2)模块的导入和使用 (1)模块是:一个模块就是一个包含 ...

  6. Python之常用模块--collections模块

    认识模块 什么是模块? 常见的场景:一个模块就是一个包含了python定义和声明的文件,文件名就是模块名字加上.py的后缀. 但其实import加载的模块分为四个通用类别: 1 使用python编写的 ...

  7. Python自动化开发之python的常用模块

    python常用模块 模块的种类:模块分为三种,分别是自定义模块:内置标准模块(即标准库):开源模块(第三方). 以下主要研究标准模块即标准库:标准库直接导入即可,不需要安装. 时间模块:time , ...

  8. python基础----常用模块

    一 time模块(时间模块)★★★★                                                      时间表现形式 在Python中,通常有这三种方式来表示时 ...

  9. python(五)常用模块学习

    版权声明:本文为原创文章,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明. https://blog.csdn.net/fgf00/article/details/52357 ...

随机推荐

  1. 使用applescript脚本方式以管理员权限运行

    - (BOOL) runProcessAsAdministrator:(NSString*)scriptPath                      withArguments:(NSArray ...

  2. 算是帮华仔写的撸JSON文件,然后发到我的REST接口的PYTHON代码

    很久没有写过类似的代码了,感觉好陌生... #!/usr/bin/python #coding:utf-8 import json import getopt import sys import re ...

  3. F - True Liars 带权并查集

    After having drifted about in a small boat for a couple of days, Akira Crusoe Maeda was finally cast ...

  4. N天学习一个linux命令之vmstat

    用途 查看系统资源整体使用情况,包括进程数量,CPU,内存,IO,swap等资源统计信息 用法 vmstat [options] [delay [ count]] 常用选项 -a 显示active/i ...

  5. 【从0開始Tornado建站】发表文章和评论

            先上个效果图: 这是每一个用户的主页.由于是基本功能.所以用户头像.爱好等信息都还没有,在下一阶段加上.右側"发表新文章"按钮点击后进入发表文章的页面: 之前尝试过 ...

  6. 关于Android开发数据存储的方式(一)

    关于Android开发数据存储方式(一) 在厦门做Android开发也有两个月了,快情人节了.我还在弄代码. 在微信平台上开发自己的APP,用到了数据存储的知识,如今总结一下: 整体的来讲.数据存储方 ...

  7. apache禁止訪问某些文件或文件夹的方法

    [apache配置禁止訪问] 1. 禁止訪问某些文件/文件夹 添加Files选项来控制,比方要不同意訪问 .inc 扩展名的文件,保护php类库: <Files ~ "\.inc$&q ...

  8. php debug二三事

    最近php相关项目遇到了一些问题,处理起来让人感觉挺有意思,寥寥记下. 1.php执行后常驻内存里,需要kill掉该进程再重启,才能让修改后的代码生效. 之前有一次组里小伙伴修改了一个长期后台进程运行 ...

  9. Project Euler:Problem 33 Digit cancelling fractions

    The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplif ...

  10. CMDBuild安装

    近日来,老板要在内部部署一套IT资产管理系统,要笔者去调研一下,测试了GLPI.OCSNG(没记错吧)和CMDBuild之后,发现还是CMDBuild的功能较为强大,虽然暂时不具备SNMP之类的工具, ...