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. ...
随机推荐
- Kettle 中的循环
说道循环,小伙伴们肯定不陌生,就是重复干一件事:而kettle中的循环一般是发生在job中,因为job是串行执行的: kettle的循环有两种,一种是通过js脚本,另外一种是通过遍历前面步骤返回的每一 ...
- oracle密码过期,改为原来的密码
我们都知道Oracle 数据库的用户的密码默认是有有效期限制的,特别是在Cloud上面的DB,有些用户是Cloud自动创建的,我们不知道原来的密码是什么,但是如果密码过期了,如果修改成新的密码,会影响 ...
- Razor页面之添加TagHelper
1.右键项目-----添加------新建项 2.创建Razor试图导入 (Razor View Imports) 3.在创建的_ViewImports.cshtml中添加 @AddTagHelpe ...
- 解决php-fpm占用cpu memory过高,开启php-fpm request_slowlog_timeout
项目刚从win下挪到linux下,发现cpu过高,内存也占用较多,以下是我解决问题的过程: 首先更改php-fpm配置 vim /usr/local/php/etc/php-fpm.conf 找到 r ...
- 2018-2019-2-20175323 java实验二《Java面向对象程序设计》
单元测试 1.在IDEA中新建项目并输入单元测试的代码 2.在IDEA中下载Junit,我发现Junit已经存在了 3.新建test文件 遇到的问题 发现Junit红字解析不了 解决办法:查找到jun ...
- Java-Class-@I:org.apache.ibatis.annotations.Mapper
ylbtech-Java-Class-@I:org.apache.ibatis.annotations.Mapper 1.返回顶部 2.返回顶部 1. package com.ylbtech.ed ...
- 永久修改 putty字体大小
修改前: 修改操作: 1. Window -> Appearance -> Font settings -> Change 修改 修改 2. 返回登陆主界面 Session ...
- 刚装完Linux就CPU占用率高
top命令发现如下三个进程占据了前三的CPU使用率 wpa_supplicant NetworkManager rsyslogd google发现前两个进程与无线网络有关,我的电脑是笔记本,插的有线, ...
- scala中闭包的使用
闭包的实质就是代码与用到的非局部变量的混合,即: 闭包 = 代码 + 用到的非局部变量 实例1: 匿名函数中引入闭包 val multiplier = (i:Int) => i * factor ...
- grep 的一些常用用法
打印匹配到的上下5行 grep -C 5 'root' /etc/passwd 上下5行 grep -A 5 'root' /etc/passwd afte ...