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的更多相关文章

  1. 20 常用模块 hashlib hmac:加密 xml xlrd xlwt:excel读|写 configparser subprocess

    hashlib模块:加密 加密: 1.有解密的加密方式 2.无解密的加密方式:碰撞检查 hashlib -- 1)不同数据加密后的结果一定不一致 -- 2)相同数据的加密结果一定是一致的 import ...

  2. Python第十一天 异常处理 glob模块和shlex模块 打开外部程序和subprocess模块 subprocess类 Pipe管道 operator模块 sorted函数 os模块 hashlib模块 platform模块 csv模块

    Python第十一天    异常处理  glob模块和shlex模块    打开外部程序和subprocess模块  subprocess类  Pipe管道  operator模块   sorted函 ...

  3. python模块之sys和subprocess以及编写简单的主机扫描脚本

    python模块之sys和subprocess以及编写简单的主机扫描脚本 1.sys模块 sys.exit(n)  作用:执行到主程序末尾,解释器自动退出,但是如果需要中途退出程序,可以调用sys.e ...

  4. Python全栈 正则表达式(re模块正则接口全方位详解)

    re模块是Python的标准库模块 模块正则接口的整体模式 re.compile 返回regetx对象 finditer fullmatch match search 返回 match对象 match ...

  5. 常用模块:hashlib,subprocess,configparser。

    一  hashlib模块 那么我们前面学习数据类型的时候,也讲了hash,可变类型不可hash:不可变类型可hash. 我们知道hash是一种算法,接收传入的内容经过运算之后得到一个hash值,我们可 ...

  6. python常用模块补充hashlib configparser logging,subprocess模块

    一.hashlib模板 Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等. 什么是摘要算法呢?摘要算法又称哈希算法.散列算法.它通过一个函数,把任意长度的数据转换为一个长度固定 ...

  7. 常用模块-----configparser & subprocess

    configparser 模块 功能:操作模块类的文件,configparser类型文件的操作类似于字典,大多数用法和字典相同. 新建文件: import configparser cfg=confi ...

  8. hashlib hmac configparser subprocess xlrd xlwt

    hashlib模块:加密 import hashlib # 基本使用 cipher = hashlib.md5('需要加密的数据的二进制形式'.encode('utf-8')) print(ciphe ...

  9. Python模块 shelve xml configparser hashlib

    常用模块1. shelve 一个字典对象模块 自动序列化2.xml 是一个文件格式 写配置文件或数据交换 <a name="hades">123</a>3. ...

随机推荐

  1. ORACLE check view

    select owner as schema_name,        view_name from sys.all_views where VIEW_NAME like 'P%' order by ...

  2. 固定Linux虚拟IP地址

    由于我的开发环境是在VMWare虚拟机里安装Centos,然后在host文件中设置拦截,这样就可以直接跳转虚拟机的CentOS,但是虚拟机的IP地址总是会变,就要随时修改host文件,很麻烦.决定虚拟 ...

  3. 使用 async await 封装微信小程序HTTP请求

    1. 编写将普通回调函数形式的方法转换为promise方法的promisic方法 // util.js const promisic = function (func) { return functi ...

  4. 【JZOJ6409】困难的图论

    description 给定由 n 个点 m 条边组成的无向连通图,保证没有重边和自环. 你需要找出所有边,满足这些边恰好存在于一个简单环中.一个环被称为简单环,当且仅当它包含的所有点都只在这个环中被 ...

  5. php获取数组中指定值的下标

    public function find_by_foreach($array,$find)//$array数组 $find需要查找的值 { foreach ($array as $key => ...

  6. Android Activity XML配置

    <activity android:name="xxxActivity" android:configChanges="keyboard|keyboardHidde ...

  7. JS自定义Array原型移除函数

    <script type="text/javascript"> //删除元素值 Array.prototype.remove = function(element){ ...

  8. bzoj1045题解

    [解题思路] (数据范围劝退?正确范围应该是n≤1000000) 设xi表示第i个小朋友给第i+1个小朋友的糖果数(特殊的,xn表示第n个小朋友给第1个小朋友的糖果数),Â表示平均糖果数,有如下方程组 ...

  9. Spring-Security (学习记录四)--配置权限过滤器,采用数据库方式获取权限

    目录 1. 需要在spring-security.xml中配置验证过滤器,来取代spring-security.xml的默认过滤器 2. 配置securityMetadataSource,可以通过ur ...

  10. P1613 跑路(倍增)

    P1613 跑路(倍增) 题目描述 小A的工作不仅繁琐,更有苛刻的规定,要求小A每天早上在6:00之前到达公司,否则这个月工资清零.可是小A偏偏又有赖床的坏毛病.于是为了保住自己的工资,小A买了一个十 ...