前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python-执行系统命令

Python-执行系统命令

作者头像
洗尽了浮华
发布2018-01-22 11:39:42
8030
发布2018-01-22 11:39:42
举报
文章被收录于专栏:散尽浮华散尽浮华

执行系统命令

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

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

call

执行命令,返回状态码。

代码语言:javascript
复制
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是每次读取多少拷贝

代码语言:javascript
复制
import shutil
s = open('test1.py')
d = open('test7.py','wb')
#d.write(s.read())
shutil.copyfileobj(s,d)

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

代码语言:javascript
复制
import shutil
shutil.copyfile('test1.py','test7.py')

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

代码语言:javascript
复制
shutil.copymode(src, dst)

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

shutil.make_archive(base_name,format….)

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

实例

代码语言:javascript
复制
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()
代码语言:js
复制
#!/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模块是用于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)

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

  • 正则表达式
  • 要匹配的字符串
  • 标志位,用于控制正则表达式的匹配方式
代码语言:javascript
复制
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)

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

代码语言:javascript
复制
import re
obj = re.search('\d+','213dsfa32134')
print obj  # <_sre.SRE_Match object at 0x0201EA30>
print obj.group() # 213

3:group和groups

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

代码语言:javascript
复制
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

代码语言:javascript
复制
import re
a = "4321fd2sa4132"
print re.findall("\d+",a)

结果:

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

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

代码语言:javascript
复制
import re
c = "32gbj4321hbj45321"
new_c = re.sub('\d+','+++',c)
print new_c
代码语言:javascript
复制
结果:+++gbj+++hbj+++

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

根据指定匹配进行分组

代码语言:javascript
复制
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

随机数

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

代码语言:javascript
复制
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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-06-08 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 执行系统命令
    • call
    • shutil
      • 次数:
      相关产品与服务
      数据库
      云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档