sys模块

# sys.argv  # 在执行程序的时候可以给程序传参数,例如类似执行nginx检测配置文件语法功能的命令, nginx -t

# mode_sys.py
import sys
print(sys.argv) # 执行程序,返回一个列表
CongdeMacBook-Pro:class_code congzhang$ python3 mode_sys.py -t
# 输出
['mode_sys.py', '-t'] ------------------------------------------------------------------
# sys.platform # 获取系统类型,比如程序要在多系统上运行的时候,就需要用到该方法了
# windows
>>> import sys
>>> print(sys.platform)
win32 # mac
>>> import sys
>>> print(sys.platform)
darwin # ubuntu
>>> import sys
>>> print(sys.platform)
linux # 应用案例:
# 假设,我们想实现一个清除终端,linux下用clear, windows下用cls import sys, os
ostype = sys.platform
# 如果系统类型为linux或mac
if ostype == ”linux” or ostype==”darwin”:
cmd=”clear”
else:
cmd=”cls”
os.system(cmd) # 调用os.system方法清屏 ------------------------------------------------------------------
# sys.path # 查看当前环境变量
>>> import sys
>>> print(sys.path)
['', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python34.zip', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/plat-darwin', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages'] # sys.path.append("/home") # 将/home添加到环境变量中,/home下面的.py文件就可以直接使用import 模块名 来进行导入了

OS模块

os.name  # 查看当前系统的类型,如果是window 则用'nt'表示,对于Linux/Unix,则用'posix'表示
>>> os.name
'posix' os.getcwd() # 得到当前工作目录,即当前Python脚本工作的目录路径
>>> os.getcwd()
'/Users/congzhang' os.listdir() # 返回指定目录下的所有文件和目录名
>>> print(os.listdir())
['.bash_history', '.bash_profile', '.bash_sessions', '.CFUserTextEncoding', '.DS_Store', '.idlerc', '.matplotlib', '.python_history', '.sogouinput', '.subversion', '.Trash', '.wiznote', 'Applications', 'Applications (Parallels)', 'data', 'Desktop', 'Documents', 'Downloads', 'Library', 'Movies', 'Music', 'Pictures', 'Public']
>>> print(os.listdir("/"))
['.DocumentRevisions-V100', '.file', '.fseventsd', '.PKInstallSandboxManager', '.Spotlight-V100', '.Trashes', '.vol', 'Applications', 'bin', 'cores', 'dev', 'etc', 'home', 'installer.failurerequests', 'Library', 'net', 'Network', 'private', 'sbin', 'System', 'tmp', 'Users', 'usr', 'var', 'Volumes'] os.remove() # 只能删除文件,括号内放文件的绝对路径,删除目录会报错的
>>> os.remove("/Users/congzhang/data/aaa") os.rmdir() # 删除指定目录
os.mkdir() # 创建目录 os.path.isfile() # 判断指定对象是否为文件,是则返回True,否则返回False
os.path.isdir() # 判断指定对象是否为目录,是则返回True,否则返回False
os.path.exists() # 检测指定对象是否存在,是则返回True,否则返回False os.system() # 运行系统命令
>>> os.system('ls')
Applications Movies
Applications (Parallels) Music
Desktop Pictures
Documents Public
Downloads data
Library
0 os.path.split() # 返回路径的目录和文件名
# 这里svn是目录,只是判断是不是以‘/’结尾,是则判定最后一个为文件,否则为目录
>>> os.path.split("/Users/congzhang/data/svn")
('/Users/congzhang/data', 'svn')
>>> os.path.split("/Users/congzhang/data/svn/")
('/Users/congzhang/data/svn', '') os.path.join(path, name) # 连接目录和文件名
>>> os.path.join("/home", "xxx.txt")
'/home/xxx.txt' os.path.basename(path) # 返回文件名
# 跟上面的os.path.split()类似,根据末尾是否存在'/'判断路径最后一段是否为目录
>>> os.path.basename("/Users/congzhang/data/svn/")
''
>>> os.path.basename("/Users/congzhang/data/svn")
'svn' os.path.abspath() # 使用相对路径获得绝对路径
>>> os.path.abspath(".")
'/Users/congzhang' os.path.dirname(path) # 返回路径的上一级目录名
>>> os.path.dirname("/Users/congzhang/data/svn")
'/Users/congzhang/data'
>>> os.path.dirname("/Users/congzhang/data/svn/")
'/Users/congzhang/data/svn'

time和datetime模块

import time
import datetime # time模块 print(time.clock()) # 输出=>3.110193534902903e-07
print(time.process_time()) # 输出=>0.031200199999999997
# 返回当前时间戳,即1970.1.1至今的秒数
print(time.time()) # 输出=>1454239454.328046 # 当前系统时间
print(time.ctime()) # 输出=>Sun Jan 31 19:24:14 2016 # 将当前时间戳转换成字符串格式的时间
print(time.ctime(time.time())) # 输出=>Sun Jan 31 19:24:14 2016 # 将时间戳转换成struct_time格式
print(time.gmtime(time.time()))
# time.struct_time(tm_year=2016, tm_mon=1, tm_mday=31, tm_hour=11, tm_min=24, tm_sec=14, tm_wday=6, tm_yday=31, tm_isdst=0) # 将本地时间的时间戳转换成struct_time格式
print(time.localtime(time.time()))
# time.struct_time(tm_year=2016, tm_mon=1, tm_mday=31, tm_hour=19, tm_min=24, tm_sec=14, tm_wday=6, tm_yday=31, tm_isdst=0) # 与上面的相反,将struct_time格式转回成时间戳格式。
print(time.mktime(time.localtime())) # 输出=>1454239454.0 # sleep
# time.sleep(4) # 将struct_time格式转成指定的字符串格式
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))) # 输出=>2016-02-01 13:53:22 # 将字符串格式转成struct_time格式
print(time.strptime("2016-02-01", "%Y-%m-%d"))
# time.struct_time(tm_year=2016, tm_mon=2, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=32, tm_isdst=-1) # datetime 模块 print(datetime.date.today()) # 输出=>2016-02-01 print(datetime.date.fromtimestamp(time.time() - 86640)) # 输出=>2016-01-31 current_time = datetime.datetime.now()
print(current_time) # 输出=>2016-02-01 14:01:02.428880 # 返回struct_time格式的时间
print(current_time.timetuple())
# time.struct_time(tm_year=2016, tm_mon=2, tm_mday=1, tm_hour=14, tm_min=1, tm_sec=41, tm_wday=0, tm_yday=32, tm_isdst=-1) # 指定替换
# datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
print(current_time.replace(2008, 8, 8)) # 输出=>2008-08-08 14:03:53.901093 # 将字符串转换成日期格式
str_to_date = datetime.datetime.strptime("2016-02-01", "%Y-%m-%d")
print(str_to_date) # 输出=>2016-02-01 00:00:00 # 比现在+10d
new_date = datetime.datetime.now() + datetime.timedelta(days=10)
print(new_date) # 输出=>2016-02-11 14:46:49.158138 # 比现在-10d
new_date = datetime.datetime.now() - datetime.timedelta(days=10)
print(new_date) # 输出=>2016-01-22 14:53:03.712109 # 比现在+10h
new_date = datetime.datetime.now() + datetime.timedelta(hours=10)
print(new_date) # 输出=>2016-02-02 00:53:03.712109 # 比现在+120s
new_date = datetime.datetime.now() + datetime.timedelta(seconds=120)
print(new_date) # 输出=>2016-02-01 14:55:03.712109

random模块

import random

print(random.random())  # 输出=>0.10518206284945941
# 包含边界
print(random.randint(1, 3)) # 输出=>2
# 不包含边界
print(random.randrange(1, 3)) # 输出=>1 # 生成4位随机验证码
check_code = ""
for i in range(4):
current = random.randrange(0, 4)
if current != i:
temp = chr(random.randint(97, 122))
else:
temp = random.randint(0, 9)
check_code = "{}{}".format(check_code, temp) print(check_code) # 输出=>oovf

json和pickle模块

pickle是Python独有的,json是各语言通用的。

import pickle
import json # 四种方法:dump、dumps、load、loads
info = {"name": "alex", "age": 18, "Limit": 10000, "created": "2016-02-01"} with open("test.txt", "wb") as f:
f.write(pickle.dumps(info)) with open("test.txt", "rb") as p:
# d1 = pickle.loads(p.read())
d1 = pickle.load(p) for k in d1:
print(k, d1[k]) if d1.get("Limit", 0) > 5000:
print("haha") # 四种方法:dump、dumps、load、loads
info = {"name": "alex", "age": 18, "Limit": 10000, "created": "2016-02-01"}
#
with open("test2.txt", "w") as f:
json.dump(info, f)
# f.write(json.dumps(info)) with open("test2.txt", "r") as p:
d2 = json.load(p) for k in d2:
print(k, d2[k])

shelve模块

shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式。

import shelve

d = shelve.open("test3.txt")

# 定义一个测试类
class TestDemo(object):
def __init__(self, n):
self.n = n t = TestDemo(123) name = ["alex", "john", "eric"] d["test1"] = name # 持久化列表
d["test2"] = t # 持久化列表 d.close()

shutil模块

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "Q1mi" """
高级的 文件、文件夹、压缩包 处理模块
""" import shutil
import os # 将文件内容(文件对象)拷贝到另一个文件中,可以指定部分拷贝
# with open("D:\qimi_WorkSpace\S12\day6\\test1.txt", "rt") as f1, open("D:\qimi_WorkSpace\S12\day6\\test2.txt", "at")as f2:
# shutil.copyfileobj(fsrc=f1, fdst=f2) # 拷贝文件
# shutil.copyfile(src="D:\qimi_WorkSpace\S12\day6\\test1.txt",dst="D:\qimi_WorkSpace\S12\day6\\test2.txt") # 仅拷贝权限。内容、组、用户均不变
# print(os.stat("D:\qimi_WorkSpace\S12\day6\\test2.txt"))
# shutil.copymode(src="D:\qimi_WorkSpace\S12\day6\\test1.txt", dst="D:\qimi_WorkSpace\S12\day6\\test2.txt")
# print(os.stat("D:\qimi_WorkSpace\S12\day6\\test2.txt")) # # 拷贝状态的信息,包括:mode bits, atime, mtime, flags
# shutil.copystat(src=,dst=)
#
# # 拷贝文件和权限
# shutil.copy(src, dst) # 拷贝文件和状态信息
# shutil.copy2(src,dst) # 递归的去拷贝文件
# shutil.ignore_patterns(*patterns)
# shutil.copytree(src, dst, symlinks=False, ignore=None) # 递归的去删除文件
# shutil.rmtree(path[, ignore_errors[, onerror]]) # 递归的去移动文件
# shutil.move(src, dst) # 创建压缩包并返回文件路径,例如:zip、tar
# shutil.make_archive(base_name, format,...) #
# base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
# 如:www =>保存至当前路径
# 如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/
# format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
# root_dir: 要压缩的文件夹路径(默认当前目录)
# owner: 用户,默认当前用户
# group: 组,默认当前组
# logger: 用于记录日志,通常是logging.Logger对象 # 将D:\qimi_WorkSpace\S12\day6目录下的文件打包成test.tar.gz,放置在当前目录
et = shutil.make_archive("test", 'gztar', root_dir='D:\\qimi_WorkSpace\\S12\\day6') # shutil模块对压缩包的处理是调用ZipFile和TarFile两个模块来进行的 # zipfile模块
import zipfile # 压缩
z = zipfile.ZipFile('test.zip', 'w')
z.write('a.log')
z.write('a.data')
z.close() # 解压
z = zipfile.ZipFile('test.zip', 'r')
z.extractall()
z.close() # tarfile模块
import tarfile # 压缩
tar = tarfile.open('test.tar','w')
tar.add('D:\\qimi_WorkSpace\\S12\\day6\\test1.tar', arcname='test1.tar')
tar.add('D:\\qimi_WorkSpace\\S12\\day6\\test2.tar', arcname='test2.tar')
tar.close() # 解压
tar = tarfile.open('test.tar','r')
tar.extractall() # 可设置解压地址
tar.close()

configparser模块

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "Q1mi"
"""
configparser 练习
""" import configparser # 写一个配置文件
config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9'} config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022' # mutates the parser
topsecret['ForwardX11'] = 'no' # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
config.write(configfile) # 读配置文件
config = configparser.ConfigParser()
print(config.sections())
a = config.read("test.cfg")
print(a)
print(config.sections())
print("bitbucket.org" in config.sections())
print(config["bitbucket.org"]["user"]) for key in config["bitbucket.org"]:
print(key, config["bitbucket.org"][key]) # 增删改查
config = configparser.ConfigParser()
config.read("test.cfg")
sec = config.sections()
print(sec) options = config.options("bitbucket.org")
print(options) item_list = config.items("bitbucket.org")
print(item_list) val = config.get("bitbucket.org", "compressionlevel")
print(val)
val = config.getint("bitbucket.org", "compressionlevel")
print(val) # 改写
config.remove_section("bitbucket.org")
config.write(open("test2.cfg", "w")) sec = config.has_section("bitbuckrt.org")
print(sec)
config.add_section("bitbucket.org")
sec = config.has_section("bitbuckrt.org")
print(sec) config.write(open("test2.cfg", "w")) config.set("bitbucket.org", 'k1', "11111")
config.write(open("test2.cfg", "w")) config.remove_option("topsecret.server.com", "port")
config.write(open("test2.cfg", "w"))

subprocess模块

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "Q1mi" """
subprocess模块的练习
""" import subprocess subprocess.run("ipconfig") # subprocess.Popen()用于执行复杂的系统命令
p = subprocess.Popen("ifconfig", shell=True, stdout=subprocess.PIPE)
print(p.stdout.read()) # 需要交互的命令用到管道PIPE
obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
obj.stdin.write(b"print('hello1')\n")
obj.stdin.write(b"print('hello2')\n")
obj.stdin.write(b"print('hello3')\n")
a = obj.communicate(timeout=10)
print(a)

xml模块

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "Q1mi" """
xml模块的练习
""" import xml.etree.ElementTree as ET # 解析xml文件
tree = ET.parse("test.xml")
# 获取根
root = tree.getroot()
print(root.tag) # 遍历xml文档
for child in root:
print(child.tag, child.attrib)
for i in child:
print(i.tag, i.text) # 只遍历year节点
for i in root.iter("year"):
print(i.tag, i.text) # 修改和删除xml文件
tree = ET.parse("test2.xml")
root = tree.getroot()

re模块

常用正则表达式符号

DOTALL,则匹配任意字符,包括换行

'^'     匹配字符开头,若指定flags MULTILINE,这种也可以匹配上(r"^a","\nabc\neee",flags=re.MULTILINE)

'$'     匹配字符结尾,或e.search("foo$","bfoo\nsdfsf",flags=re.MULTILINE).group()也可以

'*'     匹配*号前的字符0次或多次,re.findall("ab*","cabb3abcbbac")  结果为['abb', 'ab', 'a']

'+'     匹配前一个字符1次或多次,re.findall("ab+","ab+cd+abb+bba") 结果['ab', 'abb']

'?'     匹配前一个字符1次或0次

'{m}'   匹配前一个字符m次

'{n,m}' 匹配前一个字符n到m次,re.findall("ab{1,3}","abb abc abbcbbb") 结果'abb', 'ab', 'abb']

'|'     匹配|左或|右的字符,re.search("abc|ABC","ABCBabcCD").group() 结果'ABC'

'(...)' 分组匹配,re.search("(abc){2}a(123|456)c", "abcabca456c").group() 结果 abcabca456c

'\A'    只从字符开头匹配,re.search("\Aabc","alexabc") 是匹配不到的

'\Z'    匹配字符结尾,同$

'\d'    匹配数字0-9

'\D'    匹配非数字

'\w'    匹配[A-Za-z0-9]

'\W'    匹配非[A-Za-z0-9]

's'     匹配空白字符、\t、\n、\r , re.search("\s+","ab\tc1\n3").group() 结果 '\t'

'(?P<name>...)' 分组匹配 re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})","371481199306143242").groupdict("city") 结果{'province': '3714', 'city': '81', 'birthday': '1993'}

最常用的匹配语法

re.match 从头开始匹配
re.search 匹配包含
re.findall 把所有匹配到的字符放到以列表中的元素返回
re.splitall 以匹配到的字符当做列表分隔符
re.sub 匹配字符并替换
  • 反斜杠的困扰:
  • 与大多数编程语言相同,正则表达式里使用""作为转义字符,这就可能造成反斜杠困扰。假如你需要匹配文本中的字符"",那么使用编程语言表示的正则表达式里将需要4个反斜杠"\\":前两个和后两个分别用于在编程语言里转义成反斜杠,转换成两个反斜杠后再在正则表达式里转义成一个反斜杠。Python里的原生字符串很好地解决了这个问题,这个例子中的正则表达式可以使用r"\"表示。同样,匹配一个数字的"\d"可以写成r"\d"。有了原生字符串,你再也不用担心是不是漏写了反斜杠,写出来的表达式也更直观。

仅需轻轻知道的几个匹配模式

re.I(re.IGNORECASE): 忽略大小写(括号内是完整写法,下同)
M(MULTILINE): 多行模式,改变'^'和'$'的行为(参见上图)
S(DOTALL): 点任意匹配模式,改变'.'的行为

Python-05-常用模块的更多相关文章

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

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

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

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

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

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

  4. Python一些常用模块

    阅读目录 一: collections模块 二: time,datetime模块 三: random模块 四: os模块 五: sys模块 六: json,pickle 七: re正则模块 八:re模 ...

  5. python中常用模块详解二

    log模块的讲解 Python 使用logging模块记录日志涉及四个主要类,使用官方文档中的概括最为合适: logger提供了应用程序可以直接使用的接口API: handler将(logger创建的 ...

  6. Python编程-常用模块及方法

    常用模块介绍 一.time模块 在Python中,通常有这几种方式来表示时间: 时间戳(timestamp):通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量.我们运行 ...

  7. Python之常用模块学习(一)

    本节大纲: 模块介绍 time &datetime模块 random os sys shutil json & picle shelve xml处理 yaml处理 configpars ...

  8. python之常用模块

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

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

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

  10. python 之常用模块

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

随机推荐

  1. jquery模拟LCD 时钟

    查看效果网址:http://keleyi.com/keleyi/phtml/jqtexiao/24.htm 以下是HTML文件源代码: <!DOCTYPE html PUBLIC "- ...

  2. 显示快照监控:/SDF/MON

    透过SE38运行程序/SDF/MON,可以显示屏幕的监控快照:

  3. 关于arcgis engine的注记显示与关闭问题

    1.注记的添加需要拿到IGeoFeatureLayer接口下的AnnotationProperties属性,转为IAnnotationLayerPropertiesCollection接口,并创建一个 ...

  4. SQL Queries from Transactional Plugin Pipeline

    Sometimes the LINQ, Query Expressions or Fetch just doesn't give you the ability to quickly query yo ...

  5. 移动端App广告常见的10种形式

    什么是App广告?   App广告,或称In-App广告,是指智能手机和平板电脑这类移动设备中第三方应用程序内置广告,属于移动广告的子类别. App广告兴起得益于其载体—App的风行.平板电脑和大屏触 ...

  6. android handler ,message消息发送方式

    1.Message msg =  Message.obtain(mainHandler) msg.obj=obj;//添加你需要附加上去的内容 msg.what = what;//what消息处理的类 ...

  7. SqlServer--模糊查询-通配符

    查询所有姓张的同学Select * from student where left(sName,1)='张'   看上去很美,如果改成查询名字中带亮的学生怎么做?换一种做法 like  Select  ...

  8. Oracle数据泵(Data Dump)错误汇集

    Oracle数据泵(Data Dump)使用过程当中经常会遇到一些奇奇怪怪的错误案例,下面总结一些自己使用数据泵(Data Dump)过程当中遇到的问题以及解决方法.都是在使用过程中遇到的问题,以后陆 ...

  9. Ignite 配置更新Oracle JDBC Drive

           如果使用Oracle 12C 作为Ignite 的Repository的话,在Repository Createion Wizard的配置过程中,会出现ORA-28040:No matc ...

  10. 【Python】用户登录三次锁定

    这是从另外一个博客考过了的,借鉴一下,怕下次找不到1 # -*- coding:utf-8 -*- 2 3 #登录三次锁定用户 4 5 #用于计数(循环三次的判断) 6 count = 0 7 8 # ...