使用Python写简单的脚本已经有几个月了,由于不是经常写,导致每次用起来经常会忘记一些写法,现在做个笔记:
分类方法、函数作用操作系统
os.name查看操作系统类型
os.uname()函数操作系统详细信息环境变量
os.environ环境变量
os.environ.get('key')某个环境变量的值操作文件、目录
os.getcwd()获取当前目录
os.listdir( )目录列表
os.mkdir()创建文件、目录
os.rmdir()删除文件、目录
os.chdir()改变默认目录
shutil.copyfile()复制文件文件重命名、删除
os.rename()文件重命名
os.remove()文件删除
os.path模块
os.path.abspath()绝对路径
os.path.join()重组路径
os.path下拆分路径
os.path.split()拆分路径
os.path.splitext()拆分路径的扩展名
os.path下判断函数
os.path.isdir()判断目录
os.path.isfile()判断文件
#大括号转义
使用两个{{ 或 }},而不是使用\{ 或 \}
1、时间戳
import datetime(自带库)
print "# time is :", datetime.datetime.now().strftime('%Y-%m-%d%H:%M:%S')
时间格式转换,比如(10/01/2019 --> 2019-10-01)
systemInfoList = cpuResultList[0].split()
timeArray = time.strptime(systemInfoList[3], "%m/%d/%Y")
saTime=time.strftime("%Y-%m-%d", timeArray)
时间戳-->时间格式转换
saTmpFileAdjustTimeStamp = os.path.getmtime(saTmpFile)
timestampTmp = time.localtime(saTmpFileAdjustTimeStamp)
saTmpFileAdjustTime = time.strftime('%Y-%m-%d', timestampTmp)
2、打开文件使用with写法,防止忘记关闭文件句柄。
with open('project.lib') as pr:
for line in pr:
if re.search('\sreference.lib\s', line):
continue
string += line
3、Hash 数据结构最好使用get方法来得到它的值,以及访问Hash的值,以及Hash排序
DBVolume = userDB.get(userName).get('volume')
DBQtree = userDB.get(userName).get('qtree')
DBVserver = userDB.get(userName).get('vserver')
emailContent = transHuman(quotaDB.get(DBVserver).get(DBVolume).get(userName))
# 获取Hash的值
for k,v in prj.items():
print ('{k:<10} --> {v:<10}'.format(v = v ,k = k))
for k in prj.keys():
print ('{k}'.format(k = k))
# hash 排序
Sorted返回的是一个列表
dbListTmp = sorted(db.items(), key=lambda x: x[1]) #仅限于一层字典,多层需要注意但是也可以排序。
VS
import operator
dbListTmp = sorted(db.items(), key=operator.itemgetter(1))
多层排序:注意db.items()是一个元组,重点二层字典排序EX:
DBSortList = sorted(DB.items(), key=lambda x: float(x[1]['Used']))
返回值是一个列表。
另一种思路:
先把hash变成列表
stuDBList = Sorted(list[DB.items()])
取出key的值组成一个列表
stuNameList = [x[0] for x in stuDBList ]
取出Value值组成一个列表
stuCOCountList = [X[1].get("OUT") for x in stuDBList]
# 列表排序:
timeList = ['20:50:59', '2:50:59', '8:50:59', '14:50:59']
timeList = sorted(timeList, key=lambda x:int(x.split(':')[0]))
print (timeList)
# ['2:50:59', '8:50:59', '14:50:59', '20:50:59']
4、命令行参数解析最好使用自带库来解析:optParse,argparse
from optparse import OptionParse(自带库)
def option_process():
usage = "%prog [option]"
optParser = OptionParser(usage=usage)
optParser.add_option('-f', '--file', action='store', dest='cfg_name',
help='Please input the confige name, setup database',
)
optParser.add_option('-g', '--generate', action='store_true', dest='gen',
help='Output the templete confige file',
)
if not len(sys.argv[1:]):
optParser.print_help()
exit()
option, args = optParser.parse_args()
return option
import argparse
def optionProcess():
'''
input the option from the command line ,
decode the option.
'''
parser = argparse.ArgumentParser(usage='%(prog)s [options]', description='Linux sysstat sar(System Activity Reporter) log analysis script')
# parser.description=''
parser.add_argument("-v", "--version", action="version", version='%(prog)s version is 0.0')
parser.add_argument("-c", "--cpu", action="store_true", help='Output Cpu idle usage graph')
if not len(sys.argv[1:]):
parser.print_help()
exit()
args = parser.parse_args()
return args
5、正则匹配与替换:
匹配:re.search('^#|^ +#',line)
prj_exist = re.search("(^DEFINE|^INCLUDE).+/(.*?)_(pdk|cad)", prj_cont , re.M)(忽略大小写)
替换:line_list = re.sub(r'#.*',"",line).rsplit('=')
6、去掉空格和分割字符串:
cfg_list = cfg_content.strip().rsplit('\n')
7、得到当前路径|用户名、打印数据结构、合并路径、调用shell命令并得到相应的值
import sys,os,re
import pprint as pp
import getpass as gp
import commands as cmd # python 2.6, for python 3.1 transfer subprocess
from optparse import OptionParser
#sys.path.append("python")
#import NetApp
from quotaOb import quotaApi
# 打印数据结构
pp.pprint()(必须有括号)
# 得到shell命令的实行情况,和返回值
(status, userDomain) = cmd.getstatusoutput('ypwhich')
# 获得目录下的所有文件
cwd = os.getcwd()
dirList = os.listdir(cwd)
pp.pprint(dirList)
# 得到用户名
userName = gp.getuser()
# 当前路径
cwd = os.getcwd()
cwdBasename = os.path.basename(cwd)
# 去掉#注释行
if re.search('^\s*?#', line):
string += line
continue
# 合并路径
file_location = os.path.join(file_path, file_name)
Note:合并路径的除了第一项都不能以/开头,不然会丢失这一项。
# 得到path下所有的目录及其子文件
for root, dirs, files in os.walk(path, topdown=True):
for name in files:
print (os.path.join(root, name))
for name in dirs:
print (os.path.join(root, name))
8、邮件发送
import sys, smtplib
import pprint as pp
from email.MIMEText import MIMEText
from email.Header import Header
class quotaApi():
def __init__(self):
pass
def sendMail(self, content, subject, receivers):
sender = 'cadinfo@126.com.cn'
smtpIp = '192.168.34.168'
userName = 'cadinfo@126.com.cn'
passwd = 'cad'
msg = MIMEText(content,'plain', 'utf-8')
msg['Subject'] = Header(subject)
msg['From'] = sender
msg['To'] = ';'.join(receivers)
smtp = smtplib.SMTP()
smtp.connect(smtpIp)
smtp.login(userName, passwd)
smtp.sendmail(sender, receivers, msg.as_string())
smtp.quit()
9、copy文件,链接
import os,re,sys,datetime,time, shutil
import operator as op # string size comparison
import getpass as gp # get current user name
# 调用shell链接
display = os.path.join(prj_path, 'display.drf')
os.system('ln -s {0} display.drf'.format(display))
# copy 文件夹
runset = os.path.join(prj_path, 'runset')
shutil.copytree(runset,'runset',symlinks=True )
# copy 文件
cdslib = os.path.join(prj_path, 'cds.lib')
shutil.copyfile(cdslib,'cds.lib')
# setup the user preject work area directory
wa_user_name = prj_name + "_" + user_name + ".Work"
os.makedirs(wa_user_name)
os.chdir(wa_user_name)
# 打印文件夹下的所有文件
prj_name_all = os.listdir(path) # print the file name list of path
# 字符串比较
# if the input is large than current str and less than next str, return the location
if (op.lt(list_name[j],in_name)):
if (op.gt(list_name[j+1],in_name)):
insert_location = j + 1
break
20190401
10、查看环境变量及判断环境变量是否存在某值
# print os.environ['FMSOSPUBNAME']
if 'FMSOSPUBNAME' not in os.environ:
print "[FMSH_ERROR] Don't find SOS ENVIRMENT.Please user sp command !"
exit()
11、点(.)符号索引
一点提示: Python的列表是从0开始索引。 第一项的索引是0,第二项的是1,依此类推。
句点查找规则可概括为: 当模板系统在变量名中遇到点时,按照以下顺序尝试进行查找:
字典类型查找 (比如 foo["bar"] )
属性查找 (比如 foo.bar )
方法调用 (比如 foo.bar() )
列表类型索引查找 (比如 foo[bar] )
12、使用open读文件时,餐宿read, readline, readlines的区别
python文件对象提供了三个“读”方法: read()、readline() 和 readlines()。每种方法可以接受一个变量以限制每次读取的数据量。
1.read() 每次读取整个文件,它通常用于将文件内容放到一个字符串变量中。如果文件大于可用内存,为了保险起见,可以反复调用read(size)方法,每次最多读取size个字节的内容。
2.readlines() 之间的差异是后者一次读取整个文件,象 .read() 一样。.readlines() 自动将文件内容分析成一个行的列表,该列表可以由 Python 的 for ... in ... 结构进行处理。
3.readline() 每次只读取一行,通常比readlines() 慢得多。仅当没有足够内存可以一次读取整个文件时,才应该使用 readline()。
注意:这三种方法是把每行末尾的'\n'也读进来了,它并不会默认的把'\n'去掉,需要我们手动去掉。
13、由于涉及到公司邮箱,数据库账号的危险性,一般会对这类python进行加密处理,这类程序加密方案基本有
1、编译二进制代码。非常不安全,网上有在线的反编译网站,安慰新手。
2、混淆代码。出名的是GITHUB上的:git@github.com:astrand/pyobfuscate.git
3、使用C编译的方式,比较彻底。
但结合实际,可以采用2+1的方式来实现,简单容易。首先使用pyobfuscate混淆代码,但是这样要注意会修改到类的名字。
所以要手动找到类名称位置,然后使用python -m script -b来产生二进制代码,不夹-b,python3会生成一个文件夹
14、python 来使用模块打包二进制代码时,一定要注意,代码里会吧sys.path更新
直接启动是把run.py文件,所在的目录放到了sys.path属性中。
模块启动是把你输入命令的目录(也就是当前路径),放到了sys.path属性中***
15、读写编码问题
今天遇到一个问题就是python3在打开文档的时候会出现编码错误,但奇怪的是在python2时不会出现这个问题。
看了下解释,Python3默认读取的时候按照utf-8读取,python2是按照unicode来读取。
不是很明白。
最后解决方法:
with open (subFile, encoding = 'utf-8', errors='ignore') as subf:
print (type(subf))
fileConf = subf.read()
加了ignore,但是感觉这种方法不好,如果这个文件不存在会出现什么情况?如果文件不存在还是会报错。还好,但是如果编码乱了
会把乱掉的编码丢失掉。所以可能会造成数据丢失
16、print输出字体颜色字体颜色说明
17、生成随机数字符,用到两个库string和random
# 11位随机数
bit = 11
for i in range(bit):
your_pass = random.choice(string.ascii_letters + string.digits +string.punctuation)
user_list.append(your_pass)
pass_result = "".join(user_list)
18、字典的取值方法,推荐第二种
# 第一种 若键不存在则会抛出KeyError异常
person['city']
# 第二种 不会抛出异常,不存在则返回None,也可以设置默认返回值
person.get('city',"上海")
# 第三种 与第二种类似,区别在于setdefault方法会更新字典
person.setdefault('city', '上海')
19、#!/usr/bin/python VS #! /usr/bin/env python
前一种是绝对路径,直接调用/usr/bin下的python,后一种是通过env 查找path路径下的python,可能不一样。
当系统看到这一行的时候,首先会到env设置里查找python的安装路径,再调用对应路径下的解释器程序完成操作。
#!/usr/bin/python相当于写死了python路径。
#!/usr/bin/env python会去环境设置寻找python目录。
注意:
防止用户没有将python装在默认的/usr/bin路径里,推荐使用#!/usr/bin/env python。
20、linux执行python的脚本文件,提示No such file or directory,解决方法
1.使用vim打开该py文件
2.点击esc,输入:set ff
回车,显示fileformat=dos,
3.重新设置文件格式:set ff=unix
4.保存并推出:wq
21、python 跳出多重循环的方法
用for...else...语句
# -*- coding:utf-8 -*-
"""
功能:python跳出循环
"""
# 方法2:for...else...用法,用于跳出指定循环层
for i in range(5):
for j in range(5):
for k in range(5):
if i == j == k == 3:
break
else:
print i, '----', j, '----', k
else: # else1
continue
break # break1
else: # else2
continue
break # break2
解释:
(1)break能跳出某一重循环(该重循环的本次及剩余次数都不再执行),
但并不能跳出该重循环的其他外重循环。
例如,最内第3重循环break之后,程序返回第2重循环继续执行第2重的下一次,
然后第3重循环将再次执行。
(2)continue是跳过某一重循环的某一次,但该重循环的剩余次数会继续执行。
(3)for...else:其中else块中的语句将在for循环完整执行过之后才会被执行,
如果for循环被break,则else块将不会被执行。
(4)方法3中,当第3重循环满足i == j == k ==3时,第3重循环被break,则并列的else1将跳过,
执行break1,导致第2重循环被终止,则else2被跳过,执行break2,导致第1重循环被终止。
最终实现跳出整个循环。