day27 模块:正则re, configparser, subprocess
Python之路,Day15 = Python基础15
re 模块补充
ret = re.findall("c.d", "abc\nd", re.S)
# 后面参数用来修改模式,这个模式下 . 可以匹配所有的字符,包括换行符 re.split()
re.split("\d+", "hello23world12dfae3dge")
>>>["hello", "world", "dfae", "dge"]
可以第三个参数,最大分割次数。 re.split("(\d+)", "hello23world12dfae3dge")
>>>["hello", "", "world", "", "dfae", "", "dge"]
分隔符用括号括起来,可以保留分隔符 re.sub()
re.sub(old, new, str, count)
re.sub(规则, 新的内容, 处理的字符串)
有返回值? re.subn()
类似于 sub, 返回结果为一个元祖,第一个为返回的结果,第二个元素为替换的个数 re.compile() # 编译 re.finditer()
结果为可迭代对象
res = re.finditer("","")
next(res).group()
# 封装到迭代器里面的是一个个对象
configparser 模块
# 模块:用于文件处理
# 可处理的文件类似于配置文件,文件的内容类似于嵌套的字典,文件格式:
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes [bitbucket.org]
User = hg [topsecret.server.com]
Port = 50022
ForwardX11 = no
注:[DEFAULT] 为默认,里面存放的内容为下面都有的内容
用python生成这种文件
import configparser config = configparser.ConfigParser() config["DEFAULT"] = {'ServerAliveInterval': '',
'Compression': 'yes',
'CompressionLevel': '',
'ForwardX11':'yes'
} config['bitbucket.org'] = {'User':'hg'} config['topsecret.server.com'] = {'Host Port':'','ForwardX11':'no'} with open('example.ini', 'w') as configfile: config.write(configfile)
查找文件
import configparser config = configparser.ConfigParser() #---------------------------查找文件内容,基于字典的形式 print(config.sections()) # [] config.read('example.ini') print(config.sections()) # ['bitbucket.org', 'topsecret.server.com'] print('bytebong.com' in config) # False
print('bitbucket.org' in config) # True print(config['bitbucket.org']["user"]) # hg print(config['DEFAULT']['Compression']) #yes print(config['topsecret.server.com']['ForwardX11']) #no print(config['bitbucket.org']) #<Section: bitbucket.org> for key in config['bitbucket.org']: # 注意,有default会默认default的键
print(key) print(config.options('bitbucket.org')) # 同for循环,找到'bitbucket.org'下所有键 print(config.items('bitbucket.org')) #找到'bitbucket.org'下所有键值对 print(config.get('bitbucket.org','compression')) # yes get方法取深层嵌套的值
增删改操作
import configparser config = configparser.ConfigParser() config.read('example.ini') config.add_section('yuan') config.remove_section('bitbucket.org')
config.remove_option('topsecret.server.com',"forwardx11") config.set('topsecret.server.com','k1','')
config.set('yuan','k2','') config.write(open('new2.ini', "w"))
subprocess模块
调用系统命令
简单命令
import subprocess # 创建一个新的进程,与主进程不同步 if in win: s=subprocess.Popen('dir',shell=True)
s=subprocess.Popen('ls')
s.wait() # s是Popen的一个实例对象 print('ending...')
命令带参数
import subprocess subprocess.Popen('ls -l',shell=True) #subprocess.Popen(['ls','-l'])
写的时候记得加入后面的参数 shell=True,如果,在linux中不加这个参数的话,使用第三行的那个命令的时候会报错,当然,这个时候你可以使用第5行的这个方式
控制子进程
s.poll() # 检查子进程状态
s.kill() # 终止子进程
s.send_signal() # 向子进程发送信号
s.terminate() # 终止子进程 s.pid:子进程号
子进程的文本流控制
可以在Popen()建立子进程的时候改变标准输入、标准输出和标准错误,并可以利用subprocess.PIPE将多个子进程的输入和输出连接在一起,构成管道(pipe):
import subprocess # s1 = subprocess.Popen(["ls","-l"], stdout=subprocess.PIPE)
# print(s1.stdout.read()) #s2.communicate() s1 = subprocess.Popen(["cat","/etc/passwd"], stdout=subprocess.PIPE)
s2 = subprocess.Popen(["grep","0:0"],stdin=s1.stdout, stdout=subprocess.PIPE)
out = s2.communicate() print(out)
ubprocess.PIPE实际上为文本流提供一个缓存区。s1的stdout将文本输出到缓存区,随后s2的stdin从该PIPE中将文本读取走。s2的输出文本也被存放在PIPE中,直到communicate()方法从PIPE中读取出PIPE中的文本。
注意:communicate()是Popen对象的一个方法,该方法会阻塞父进程,直到子进程完成
快捷API
'''
subprocess.call() 父进程等待子进程完成
返回退出信息(returncode,相当于Linux exit code) subprocess.check_call()
父进程等待子进程完成
返回0,检查退出信息,如果returncode不为0,则举出错误subprocess.CalledProcessError,该对象包含
有returncode属性,可用try…except…来检查 subprocess.check_output()
父进程等待子进程完成
返回子进程向标准输出的输出结果
检查退出信息,如果returncode不为0,则举出错误subprocess.CalledProcessError,该对象包含
有returncode属性和output属性,output属性为标准输出的输出结果,可用try…except…来检查。 '''
以上代码来自:http://www.cnblogs.com/yuanchenqi/articles/6766020.html
如有侵权,请联系我,立马删除
day27 模块:正则re, configparser, subprocess的更多相关文章
- 20 常用模块 hashlib hmac:加密 xml xlrd xlwt:excel读|写 configparser subprocess
hashlib模块:加密 加密: 1.有解密的加密方式 2.无解密的加密方式:碰撞检查 hashlib -- 1)不同数据加密后的结果一定不一致 -- 2)相同数据的加密结果一定是一致的 import ...
- Python第十一天 异常处理 glob模块和shlex模块 打开外部程序和subprocess模块 subprocess类 Pipe管道 operator模块 sorted函数 os模块 hashlib模块 platform模块 csv模块
Python第十一天 异常处理 glob模块和shlex模块 打开外部程序和subprocess模块 subprocess类 Pipe管道 operator模块 sorted函 ...
- python模块之sys和subprocess以及编写简单的主机扫描脚本
python模块之sys和subprocess以及编写简单的主机扫描脚本 1.sys模块 sys.exit(n) 作用:执行到主程序末尾,解释器自动退出,但是如果需要中途退出程序,可以调用sys.e ...
- Python全栈 正则表达式(re模块正则接口全方位详解)
re模块是Python的标准库模块 模块正则接口的整体模式 re.compile 返回regetx对象 finditer fullmatch match search 返回 match对象 match ...
- 常用模块:hashlib,subprocess,configparser。
一 hashlib模块 那么我们前面学习数据类型的时候,也讲了hash,可变类型不可hash:不可变类型可hash. 我们知道hash是一种算法,接收传入的内容经过运算之后得到一个hash值,我们可 ...
- python常用模块补充hashlib configparser logging,subprocess模块
一.hashlib模板 Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等. 什么是摘要算法呢?摘要算法又称哈希算法.散列算法.它通过一个函数,把任意长度的数据转换为一个长度固定 ...
- 常用模块-----configparser & subprocess
configparser 模块 功能:操作模块类的文件,configparser类型文件的操作类似于字典,大多数用法和字典相同. 新建文件: import configparser cfg=confi ...
- hashlib hmac configparser subprocess xlrd xlwt
hashlib模块:加密 import hashlib # 基本使用 cipher = hashlib.md5('需要加密的数据的二进制形式'.encode('utf-8')) print(ciphe ...
- Python模块 shelve xml configparser hashlib
常用模块1. shelve 一个字典对象模块 自动序列化2.xml 是一个文件格式 写配置文件或数据交换 <a name="hades">123</a>3. ...
随机推荐
- 【POJ】1287 Networking
题目链接:http://poj.org/problem?id=1287 题意:n个点,m条网线长度.求构成网络的最小网线长度. 题解:最小生成树裸题.套板子. 代码: #include<iost ...
- jq容易混淆点
jQuery链式编程: 原:把当前元素颜色修改为红色,其余兄弟颜色不变 $(this).css("color",'red') ; $(this).siblings().css(&q ...
- xinetd - 扩展的互联网服务守护进程
总览 SYNOPSIS xinetd [options] 描述 DESCRIPTION xinetd 执行与 inetd 相同的任务:它启动提供互联网服务的程序.与在系统初始化时启动这些服务器,让它们 ...
- 关于hadoop多次format之后,会出现的dataNode消失问题
如标题,最近我由于想初始化以下hadoop集群,之后却发现启动集群后所有的DataNode都消失了. 问题查找: 由于时所有的DataNode都出了问题,于是我翻找了以下DataNode的日志(默认在 ...
- vue之自定义指令
1.自定义指令的作用 除了核心功能默认内置的指令 (v-model 和 v-show),Vue 也允许注册自定义指令.注意,在 Vue2.0 中,代码复用和抽象的主要形式是组件.然而,有的情况下,你仍 ...
- Web API 接口参考
Web API 接口参考:https://developer.mozilla.org/zh-CN/docs/Web/API
- Bootstrap快速入门并且建立常用模板
对于移动端,能够快速搭建网站,操作相对简单 ,更容易掌握,这篇文章就介绍一下BootStrap 一 什么是Bottstrap 一个前端开发的框架,Bootstrap,来自 Twitter,是目前很受 ...
- Delphi中关于菜单的几个技巧
-- 1将菜单项移到菜单栏的最右边 在一些应用程序中,常把一些特殊的菜单项放在菜单栏的最右边(如WPS2000 中的"定制界面"菜单,一些应用程序的帮助菜单),这些菜单项放在菜单栏 ...
- (转)在eclipse中将android项目生成apk并且给apk签名
转:http://www.cnblogs.com/tianguook/archive/2012/09/27/2705724.html 生成apk最懒惰的方法是:只要你运行过android项目,到工作目 ...
- row_number() over(partition by a order by b desc) rn 用法
转载于:http://www.blogjava.net/kxbin/articles/360195.html 可以看看http://jingyan.baidu.com/article/9989c746 ...