Python-执行系统命令

本文涉及的产品
日志服务 SLS,月写入数据量 50GB 1个月
简介:

 

 

执行系统命令

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

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

call

执行命令,返回状态码。

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

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

shutil

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

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

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

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

 

import shutil
shutil.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 re
obj = re.match('\d+','213dsfa32134')
print obj  # <_sre.SRE_Match object at 0x0201EA30>
print obj.group() # 213

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

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

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

3:group和groups

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

复制代码
复制代码
import re
a = "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 re
a = "4321fd2sa4132"
print re.findall("\d+",a)

结果:

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

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

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

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

根据指定匹配进行分组

复制代码
复制代码
import re
content = "'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 random
checkcode = ''
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
  
***************当你发现自己的才华撑不起野心时,就请安静下来学习吧***************
分类:  Python

本文转自散尽浮华博客园博客,原文链接:http://www.cnblogs.com/kevingrace/p/5569976.html ,如需转载请自行联系原作者
相关实践学习
通过日志服务实现云资源OSS的安全审计
本实验介绍如何通过日志服务实现云资源OSS的安全审计。
相关文章
|
3月前
|
机器学习/深度学习 监控 算法
基于mediapipe深度学习的手势数字识别系统python源码
本内容涵盖手势识别算法的相关资料,包括:1. 算法运行效果预览(无水印完整程序);2. 软件版本与配置环境说明,提供Python运行环境安装步骤;3. 部分核心代码,完整版含中文注释及操作视频;4. 算法理论概述,详解Mediapipe框架在手势识别中的应用。Mediapipe采用模块化设计,包含Calculator Graph、Packet和Subgraph等核心组件,支持实时处理任务,广泛应用于虚拟现实、智能监控等领域。
|
25天前
|
安全 JavaScript Java
Python中None与NoneType的真相:从单例对象到类型系统的深度解析
本文通过10个真实场景,深入解析Python中表示“空值”的None与NoneType。从单例模式、函数返回值,到类型注解、性能优化,全面揭示None在语言设计与实际编程中的核心作用,帮助开发者正确高效地处理“无值”状态,写出更健壮、清晰的Python代码。
118 3
|
6月前
|
前端开发 JavaScript 关系型数据库
基于Python+Vue开发的商城管理系统源码+运行步骤
基于Python+Vue开发的商城管理系统(前后端分离),这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Python编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Python的网上商城管理系统项目,大学生可以在实践中学习和提升自己的能力,为以后的职业发展打下坚实基础。
188 7
|
2月前
|
算法 数据可视化 数据挖掘
基于EM期望最大化算法的GMM参数估计与三维数据分类系统python源码
本内容展示了基于EM算法的高斯混合模型(GMM)聚类实现,包含完整Python代码、运行效果图及理论解析。程序使用三维数据进行演示,涵盖误差计算、模型参数更新、结果可视化等关键步骤,并附有详细注释与操作视频,适合学习EM算法与GMM模型的原理及应用。
|
前端开发 关系型数据库 MySQL
基于python“花开富贵”花园管理系统
感谢大学同学的陪伴与帮助,在我独立编写毕业论文期间,大学同学的鼓励与耐心的帮助使得我少走很多弯路,节省毕业论文的编写时间,也让我有更多精力去完善我开发的系统。 在整个系统开发过程中,我周围的同学和朋友给了我很多意见,所以我很快就确认了系统的商业思想。在次,我由衷的向他们表示感激。
35 0
|
5月前
|
前端开发 JavaScript 关系型数据库
基于python的租房网站-房屋出租租赁系统(python+django+vue)源码+运行
该项目是基于python/django/vue开发的房屋租赁系统/租房平台,作为本学期的课程作业作品。欢迎大家提出宝贵建议。
157 6
|
5月前
|
前端开发 JavaScript 关系型数据库
基于Python+Vue开发的美容预约管理系统源码+运行
基于Python+Vue开发的美容预约管理系统(前后端分离),这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Python编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Python的美容诊所预约管理系统项目,大学生可以在实践中学习和提升自己的能力,为以后的职业发展打下坚实基础。
86 9
|
5月前
|
JavaScript 前端开发 关系型数据库
基于Python+Vue开发的体育场馆预约管理系统源码+运行
本项目为大学生课程设计作业,采用Python和Vue技术构建了一个体育场馆预约管理系统(实现前后端分离)。系统的主要目标在于帮助学生理解和掌握Python编程知识,同时培养其项目规划和开发能力。参与该项目的学习过程,学生能够在实际操作中锻炼技能,为未来的职业发展奠定良好的基础。
128 3
|
5月前
|
前端开发 JavaScript 关系型数据库
基于Python+Vue开发的摄影网上预约管理系统源码+运行
基于Python+Vue开发的摄影网上预约管理系统(前后端分离),影楼婚纱摄影,这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Python编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Python的在线摄影预约管理系统项目,大学生可以在实践中学习和提升自己的能力,为以后的职业发展打下坚实基础。
91 8

热门文章

最新文章

推荐镜像

更多