day27 模块:正则re, configparser, subprocess

Python之路,Day15 = Python基础15

 

re 模块补充

 1 ret = re.findall("c.d", "abc\nd", re.S)     
 2     # 后面参数用来修改模式,这个模式下 . 可以匹配所有的字符,包括换行符
 3 
 4 
 5 
 6 re.split()
 7     re.split("\d+", "hello23world12dfae3dge")
 8     >>>["hello", "world", "dfae", "dge"]
 9     可以第三个参数,最大分割次数。
10 
11     re.split("(\d+)", "hello23world12dfae3dge")
12     >>>["hello", "23", "world", "12", "dfae", "3", "dge"]
13     分隔符用括号括起来,可以保留分隔符
14     
15     
16 re.sub()
17     re.sub(old, new, str, count)
18     re.sub(规则, 新的内容, 处理的字符串)
19     有返回值?
20     
21 re.subn()
22     类似于 sub, 返回结果为一个元祖,第一个为返回的结果,第二个元素为替换的个数
23 
24 
25 re.compile()      # 编译
26     
27 re.finditer()
28     结果为可迭代对象
29     res = re.finditer("","")
30     next(res).group()
31     # 封装到迭代器里面的是一个个对象

 

configparser 模块

  # 模块:用于文件处理
  # 可处理的文件类似于配置文件,文件的内容类似于嵌套的字典,文件格式:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
  
[bitbucket.org]
User = hg
  
[topsecret.server.com]
Port = 50022
ForwardX11 = no
注:[DEFAULT] 为默认,里面存放的内容为下面都有的内容

用python生成这种文件

 1 import configparser
 2 
 3 config = configparser.ConfigParser()
 4 
 5 config["DEFAULT"] = {'ServerAliveInterval': '45',
 6                       'Compression': 'yes',
 7                      'CompressionLevel': '9',
 8                      'ForwardX11':'yes'
 9                      }
10 
11 config['bitbucket.org'] = {'User':'hg'}
12 
13 config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'}
14 
15 with open('example.ini', 'w') as configfile:
16 
17    config.write(configfile)

 

 查找文件

 1 import configparser
 2 
 3 config = configparser.ConfigParser()
 4 
 5 #---------------------------查找文件内容,基于字典的形式
 6 
 7 print(config.sections())        #  []
 8 
 9 config.read('example.ini')
10 
11 print(config.sections())        #   ['bitbucket.org', 'topsecret.server.com']
12 
13 print('bytebong.com' in config) # False
14 print('bitbucket.org' in config) # True
15 
16 
17 print(config['bitbucket.org']["user"])  # hg
18 
19 print(config['DEFAULT']['Compression']) #yes
20 
21 print(config['topsecret.server.com']['ForwardX11'])  #no
22 
23 
24 print(config['bitbucket.org'])          #<Section: bitbucket.org>
25 
26 for key in config['bitbucket.org']:     # 注意,有default会默认default的键
27     print(key)
28 
29 print(config.options('bitbucket.org'))  # 同for循环,找到'bitbucket.org'下所有键
30 
31 print(config.items('bitbucket.org'))    #找到'bitbucket.org'下所有键值对
32 
33 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','11111')
config.set('yuan','k2','22222')

config.write(open('new2.ini', "w")) 

 

subprocess模块

  调用系统命令

简单命令

1 import subprocess
2 
3 #  创建一个新的进程,与主进程不同步  if in win: s=subprocess.Popen('dir',shell=True)
4 s=subprocess.Popen('ls')
5 s.wait()                  # s是Popen的一个实例对象
6 
7 print('ending...')  

命令带参数

1 import subprocess
2 
3 subprocess.Popen('ls -l',shell=True)
4 
5 #subprocess.Popen(['ls','-l'])

写的时候记得加入后面的参数 shell=True,如果,在linux中不加这个参数的话,使用第三行的那个命令的时候会报错,当然,这个时候你可以使用第5行的这个方式

控制子进程

1 s.poll() # 检查子进程状态
2 s.kill() # 终止子进程
3 s.send_signal() # 向子进程发送信号
4 s.terminate() # 终止子进程
5 
6 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

如有侵权,请联系我,立马删除

posted on 2017-06-27 17:21  何必从头  阅读(194)  评论(0编辑  收藏  举报

导航