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. ...
随机推荐
- Center OS 部署Tomcat服务
一.下载tomcat tomcat官网下载软件包,官网:https://tomcat.apache.org/ 点击download,进入下载页面,下载如下版本: 下载完成后用ftp上传到服务器,SSH ...
- JAVA去除抖音视频的水印源码!!!
@PostMapping("geturl") public DataResponse decodeDouiyin(@RequestBody DouyinRequest req ) ...
- WPF 模仿 UltraEdit 文件查看器系列 开篇和导读
WPF 模仿 UltraEdit 文件查看器系列 开篇和导读 运行环境:Win10 x64, NetFrameWork 4.8, 作者:乌龙哈里,日期:2019-05-10 学 .Net FrameW ...
- NX二次开发-获取WCS标识UF_CSYS_ask_wcs
NX9+VS2012 #include <uf.h> #include <uf_csys.h> UF_initialize(); //获取WCS标识 tag_t WcsId = ...
- 2019/11/12 CSP模拟赛&&考前小总结
写在前面的总结 离联赛只有几天了,也马上就要回归文化课了. 有点舍不得,感觉自己的水平刚刚有点起色,却又要被抓回文化课教室了,真想在机房再赖几天啊. 像19/11/11那场的简单题,自己还是能敲出一些 ...
- Java-Class-@I:org.junit.runner.RunWith
ylbtech-Java-Class-@I:org.junit.runner.RunWith 1.返回顶部 2.返回顶部 3.返回顶部 4.返回顶部 1. package org.juni ...
- Java-Class-C:org.springframework.http.ResponseEntity
ylbtech-Java-Class-C:org.springframework.http.ResponseEntity 1.返回顶部 1. org.springframework.http Clas ...
- (转)Python学习笔记(1)__name__变量
Python使用缩进对齐组织代码的执行,所有没有缩进的代码,都会在载入时自动执行.每个文件(模块)都可以任意写一些没有缩进的代码,并在载入时自动执行.为了区分 主执行代码和被调用文件,Python引入 ...
- AtCoder ABC 132E Hopscotch Addict
题目链接:https://atcoder.jp/contests/abc132/tasks/abc132_e 题目大意 给定一张 N 个点 M 条边无自环无重边的一张有向图,求从起点 S 能否三步三步 ...
- 剑指offer——25链表中环的入口节点
题目描述 给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null. 题解: 使用快慢指针即可,若快慢指针会相遇,则有环,否则快指针先到空节点: 此时,快指针从此处一次移一步遍历, ...