博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python-执行系统命令
阅读量:7225 次
发布时间:2019-06-29

本文共 7718 字,大约阅读时间需要 25 分钟。

 

 

执行系统命令

  • os.system
  • os.spawn*
  • os.popen
  • popen2.*
  • commands.*

后面三个已经废弃,以上执行shell命令的相关的模块和函数的功能均在subprocess模块中实现,并提供了更加丰富的功能

call

执行命令,返回状态码。

import subprocessret1 = subprocess.call(["ls","-l"],shell=False)print ret1ret2 = subprocess.call("ls -l",shell=True)print ret2

shell = True ,允许shell命令是字符串形式(是使用系统自带的shell)

shutil

高级的文件、文件夹、压缩包处理模块

shutil.copyfileobj(fsrc,fdst,length)将文件内容拷贝到另一个文件中,length是每次读取多少拷贝

import shutils = open('test1.py')d = open('test7.py','wb')#d.write(s.read())shutil.copyfileobj(s,d)

shutil.copyfile(src,dst)拷贝文件

 

import shutilshutil.copyfile('test1.py','test7.py')

尽拷贝权限,内容组用户均不变

shutil.copymode(src, dst)

创建压缩包并返回文件路径

shutil.make_archive(base_name,format….)

  • base_name:压缩包的文件名,也可以是压缩包的路径,当只是文件名时,则保存在当前目录,否则保存至指定路径
  • format:压缩包的种类 zip tar batar  gztar
  • root_dir: 要压缩的文件夹路径,默认是当前目录

实例

import shutil# 将/user/local/ftp下面的文件www打包放置在当前程序目录ret = shutil.make_archive("www",'tar',root_dir='/user/local/ftp')# 将/user/local/ftp下面的文件www打包放置在/user/local目录ret2 = shutil.make_archive("/user/loca/www",'tar',root_dir='/user/local/ftp')

shutil对压缩包的处理是调用ZipFile和TarFile两个模块来进行的

1
2
3
4
5
6
7
8
9
10
import 
zipfile
# 压缩
z
= 
zipfile.ZipFile(
'll.zip'
,
'w'
)
z.write(
'test1.py'
)
z.write(
'test2.py'
)
z.close()
# 解压
j
= 
zipfile.ZipFile(
'll.zip'
,
'r'
)
j.extractall()
j.close()

 

1
2
3
4
5
6
7
8
9
10
import 
tarfile
# 压缩
tar
= 
tarfile.
open
(
'y.tar'
,
'w'
)
tar.add(
'/usr/local/1.zip'
,arcname
=
'1.zip'
)
tar.add(
'/usr/local/2.zip'
,arcname
=
'2.zip'
)
tar.close()
# 解压
tar
= 
tarfile.
open
(
'y.tar'
,
'r'
)
tar.extractall()
tar.close()

ConfigParser

用于对特定的配置进行操作,当前模块的名称在python3.x版本中变更为configparser

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/usr/bin/env python
# coding:utf-8
# 用于对特定的配置进行操作,当前模块的名称在 python 3.x 版本中变更为 configparser。
import 
ConfigParser
config
= 
ConfigParser.ConfigParser()
config.read(
'goods.txt'
)
##########读操作######
# 获取模块的名称
secs
= 
config.sections()
print 
secs
# 结果:['section1', 'section2']
# 获取指定模块的key值
options
= 
config.options(
'section1'
)
print 
options
# 结果:['k1', 'k2']
# 获取指定模块下的items
item_list
= 
config.items(
'section1'
)
print 
item_list
# 结果:[('k1', 'v1'), ('k2', 'v2')]
# 获取指定模块下的key的值
val
= 
config.get(
'section1'
,
'k2'
)
print 
val
#########写操作############
# 删除一个section模块
sec
=
config.remove_section(
'car'
)
config.write(
open
(
'i.txt'
,
'w'
))
# 添加section模块。查看一个section是否存在;不存在则添加
sec
= 
config.has_section(
'car1'
)
print 
sec
# False:表示不存在
sec
= 
config.add_section(
'car1'
)
sec
= 
config.has_section(
'car1'
)
print 
sec
# True: 表示不存在
config.write(
open
(
'i.txt'
,
'w'
))
# 添加seection下面的key-value
config.
set
(
'car'
,
'k1'
,
111111111
)
config.write(
open
(
'1.txt'
,
"w"
))
# 删除section下面的key值为baoma
config.remove_option(
'car'
,
'baoma'
)
config.write(
open
(
'1.txt'
,
"w"
))

logging

用于便捷记录日志且线程安全的模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/env python
# coding:utf-8
import 
logging
logging.basicConfig(filename
=
'1.log'
,
                    
format
=
'%(asctime)s - %(name)s - %(levelname)s - %(module)s - %(message)s'
,
                    
datefmt
=
'%Y-%m-%d %H:%M:%S %p'
,
                    
# level=logging.CRITICAL,
                    
level
=
40
,
                    
)
logging.debug(
'debugdebugdebugdebugdebug'
)
logging.info(
'infoinfoinfoinfoinfoinfoinfo'
)
logging.warning(
'warningwarningwarningwarning'
)
logging.error(
'errorerrorerrorerrorerrorerror'
)
logging.critical(
'criticalcriticalcriticalcritical'
)
logging.log(
50
,
'asdfghjkl'
)

解读:

1:filename创建日志文件,然后以追加的方式接收

2:format格式:时间-用户-日志级别-哪个模块的日志-日志信息

3:时间格式:2015-12-09 11:00:28 AM

4:日志级别:可以使用数字,也可以直接指定

日志级别对应表:

CRITICAL = 50

ERROR = 40

WARNING = 30

INFO = 20

DEBUG = 10

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/usr/bin/env python
# coding:utf-8
import 
logging
logging.basicConfig(filename
=
'1.log'
,
                    
format
=
'%(asctime)s - %(name)s - %(levelname)s - %(module)s - %(message)s'
,
                    
datefmt
=
'%Y-%m-%d %H:%M:%S %p'
,
                    
# level=logging.CRITICAL,
                    
level
=
logging.DEBUG,
                    
)
while 
True
:
    
option
= 
raw_input
(
"请输入数字"
)
    
if 
option.isdigit():
        
print 
"是数字"
,option
        
logging.info(
'孩子输入的是数字'
)
    
else
:
        
logging.error(
'孩子,你是不是傻'
)

结果:

2015-12-09 13:23:39 PM - root - ERROR - test8 - 孩子,你是不是傻

2015-12-09 13:24:30 PM - root - ERROR - test8 - 孩子,你是不是傻
2015-12-09 13:24:31 PM - root - INFO - test8 - 孩子输入的是数字
2015-12-09 13:24:42 PM - root - INFO - test8 - 孩子输入的是数字

time datetime

时间相关的操作

时间有三种表示方式:

  • 时间戳 1970年1月1日之后的秒 time.time()

  • 格式化的字符串 2015-12-12 12:12

  • 结构化时间 元组包含了:年、月、日、星期等 time.struct_time time.localtime()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/usr/bin/env python
# coding:utf-8
import 
time
import 
datetime
print 
time.time()
# 1449631804.64
print 
time.strftime(
'%Y-%m-%d %H-%M-%S %p'
)
# 默认是当前时间2015-12-09 11-04-30 AM
print 
time.localtime()
# time.struct_time(tm_year=2015, tm_mon=12, tm_mday=9, tm_hour=11, tm_min=31, tm_sec=55, tm_wday=2, tm_yday=343, tm_isdst=0)
print 
time.strptime(
'2014-11-11'
,
'%Y-%m-%d'
)
# 将格式化时间转成结构化时间
 
# 日期到时间戳的转化
t
= 
datetime.datetime(
2015
,
11
,
14
,
14
,
14
)
print 
type
(
't'
)
# <type 'str'>
ti
= 
time.mktime(t.timetuple())
print 
ti 
# 1447481640.0
# 时间戳到日期的转化
tt
= 
time.localtime()
print 
tt
timestr
= 
time.strftime(
'%Y-%m-%d %H:%M:%S'
)
print 
timestr
# 2015-12-09 13:53:23

 

re

re模块是用于python的正则表达式的操作

字符:

  1. .匹配除换行符意外的任意字符

  2. \w匹配字母或数字或下划线或汉字

  3. \s匹配任意的空白符

  4. \d匹配数字

  5. \b匹配单词的开始或结束

  6. ^匹配字符串的开始

  7. $匹配字符串的结束

次数:

  1. *重复零次或更多次

  2. +重复一次或更多次

  3. ?重复零次或一次

  4. {n}重复n次

  5. {n,}重复n次或更多次

  6. {n,m}重复n到m次

1:match(pattern,string,flahs=0)

从起始位置开始根据模型去字符串中匹配指定内容,匹配单个

  • 正则表达式

  • 要匹配的字符串

  • 标志位,用于控制正则表达式的匹配方式

import reobj = re.match('\d+','213dsfa32134')print obj  # <_sre.SRE_Match object at 0x0201EA30>print obj.group() # 213

2:search(pattern,string,flahs=0)

根据模版去字符串中匹配指定内容,匹配单个

import reobj = re.search('\d+','213dsfa32134')print obj  # <_sre.SRE_Match object at 0x0201EA30>print obj.group() # 213

3:group和groups

返回一个或多个子组。如果参数为一个,就返回一个子串;如果参数有多个,就返回多个子串组成的元组

import rea = "4321fdsa4132"print re.search("([0-9]*)([a-z]*)([0-9]*)",a).group()print re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(0)print re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(1)print re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(2)print re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(3)print re.search("([0-9]*)([a-z]*)([0-9]*)",a).groups()

结果:

4321fdsa4132

4321fdsa4132

4321

fdsa

4132

('4321', 'fdsa', '4132')

4:findall(pattern,string,flahs=0)

match和search只能匹配字符串中的一个,如果想要匹配到字符串中所有符合条件的元素,则需要使用findall

import rea = "4321fd2sa4132"print re.findall("\d+",a)

结果:

['4321', '2', '4132']

5:sub(pattern,repl,string,count=0,flag=0)用于替换匹配的字符串

import rec = "32gbj4321hbj45321"new_c = re.sub('\d+','+++',c)print new_c
结果: +++gbj+++hbj+++

6:split(pattern,string,maxsplit=0,flags=0)

根据指定匹配进行分组

import recontent = "'1 - 2 * ((60-30+1*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2) )'"new_content = re.split('\*',content)print new_content# ["'1 - 2 ", ' ((60-30+1', '(9-2', '5/3+7/3', '99/4', '2998+10', '568/14))-(-4', '3)/(16-3', "2) )'"]new_content1= re.split('[\+\-\*\/]+',content)print new_content1# ["'1 ", ' 2 ', ' ((60', '30', '1', '(9', '2', '5', '3', '7', '3', '99', '4', '2998', '10', '568', '14))', '(', '4', '3)', '(16', '3', "2) )'"]a = "'1 - 2 * ((60-30+1*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2) )'"new_a = re.sub('\s*','',a)print new_a# '1-2*((60-30+1*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'new_1 = re.split('\(([\+\-\*\/]?\d+[\+\-\*\/]?\d+)\)',new_a,1)print new_1# ["'1-2*((60-30+1*(9-2*5/3+7/3*99/4*2998+10*568/14))-", '-4*3', "/(16-3*2))'"]

random

随机数

它会自动生成四位数字字母组合的字符串

import randomcheckcode = ''for i in range(4):    current =  random.randrange(0,4)    if current != i:        temp =  chr(random.randint(65,90))    else:        temp = random.randint(0,9)    checkcode += str(temp)print checkcode
1
  
***************当你发现自己的才华撑不起野心时,就请安静下来学习吧***************
分类: 
本文转自散尽浮华博客园博客,原文链接:http://www.cnblogs.com/kevingrace/p/5569976.html
,如需转载请自行联系原作者
你可能感兴趣的文章
Java版冒泡排序法
查看>>
关于FB4.6插件安装后默认语言环境的更改问题
查看>>
免费分区助手
查看>>
Javascript通过Name调用Function
查看>>
统计当前在线用户数量
查看>>
IntelliJ IDEA 乱码解决方案 (项目代码、控制台等)
查看>>
PHP项目记录
查看>>
.net面试题系列文章七(附答案)
查看>>
FastSocket
查看>>
ionic $ionicSlideBoxDelegate 滑动框事件
查看>>
点击文字,把input type="radio"也选中
查看>>
第一章 Java多线程技能
查看>>
Java 集合系列-第八篇-Map架构
查看>>
springmvc 3.2 @MatrixVariable bug 2
查看>>
React-Native PanResponder手势识别器
查看>>
IOS11 光标错位问题
查看>>
如何设计用户登录
查看>>
linux安装mysql5.7.19
查看>>
Zookeeper+ActiveMQ 集群实现
查看>>
加权有向图问题2----多源最短路径问题(Floyd算法)和关键路径算法
查看>>