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. 安装Hama的基本过程

  2. true - (成功的)什么都不做

    总览 (SYNOPSIS) true [忽略命令行参数] true OPTION 描述 (DESCRIPTION) 程序 结束 时, 产生 表示 成功 的 状态码. 下列的 选项 没有 简写 形式. ...

  3. UartAssist串口调试工具

    第一步安装UartAssist 第二步打开UartAssist 界面为 我们将我们的wifi模块连接电脑, 查看的端口号通过计算机管理设备管理器进行查看 根据要求发送数据 就可以了

  4. leetcood学习笔记-102-二叉树的层次遍历

    题目描述: 方法一; class Solution(object): def levelOrder(self, root): """ :type root: TreeNo ...

  5. mysql 存储过程 随笔

    CREATE PROCEDURE `g2`( in sts int,in type int, code varchar(20),in s int)begin declare i int; declar ...

  6. bzoj1001题解

    [解题思路] 显然,这题的答案是这个网格图的最小割.根据最大流-最小割定理,我们可以用网络流算法来求其最小割,时间复杂度最小为O(V2√E). 特殊的,这个网格图是一个平面图,于是可以根据平面图最小割 ...

  7. 几道51nod上据说是提高组难度的dp题

    1409 加强版贪吃蛇 听着懵逼做着傻逼. 每个格子只能经过一次,穿过上下界答案清0,不考虑穿的话就随便dp.如果要穿就是从尽可能上面的位置穿过上界,尽可能下面的位置穿过下界. 那么转移这一列之前找一 ...

  8. scrapy爬取cnblogs文章列表

    scrapy爬取cnblogs文章 目标任务 安装爬虫 创建爬虫 编写 items.py 编写 spiders/cnblogs.py 编写 pipelines.py 编写 settings.py 运行 ...

  9. jQuery 快捷操作

    快捷操作 1. class属性值操作 $().attr(‘class’,值); $().attr(‘class’); $().removeAttr(‘class’);  //删除class的所有属性 ...

  10. 1-MySQL高级-视图

    视图 1. 问题 对于复杂的查询,往往是有多个数据表进行关联查询而得到,如果数据库因为需求等原因发生了改变,为了保证查询出来的数据与之前相同,则需要在多个地方进行修改,维护起来非常麻烦 解决办法:定义 ...