记录python在linux操作系统上最常用的模块
一、os模块
os模块提供了一些方便使用操作系统相关功能的函数。
如下,操作目录或文件直接使用os模块的方法;操作路径类的使用os.path模块;
二、subprocess模块
subprocess 模块是可以操作进程
1、subprocess.Popen 类;创建进程,并与进程进行复杂的交互
subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False,
startupinfo=None, creationflags=0)
参数args可以是字符串或者序列类型(如:list,元组)
Popen类有很多属性,例如:
1.1、Popen.kill() 杀死子进程
1.2、Popen.stdin 参数stdin被设置为PIPE,Popen.stdin将返回一个文件对象
1.3、Popen.stdout 参数stdout被设置为PIPE,Popen.stdout将返回一个文件对象
1.4、Popen.pid 获取子进程的进程ID
2、supprocess.call(*popenargs, **kwargs) 函数;等待到子进程运行结束,并返回进程的returncode;子进程不需要进行交互,就可以使用该函数来创建
两个Popen和call例子:
subprocess.Popen
import subprocess
import logging
def getPid(process):
cmd = "ps aux | grep '%s' | grep -v grep " % process
logging.info(cmd)
out = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
infos = out.stdout.read().splitlines()
pidlist = []
if len(infos) >= 1:
for i in infos:
pid = i.split()[1]
if pid not in pidlist:
pidlist.append(pid)
return pidlist
else:
return -1
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
gameproc = ["nginx"]
for process in gameproc:
pid = getPid(process)
print(pid)
subprocess.call
import os
import subprocess
from time import strftime
logsdir = '/tmp/liu'
for files in os.listdir(logsdir):
if files.endswith(".log"):
files1 = files + "." + strftime("%Y-%m-%d") + ".zip"
os.chdir(logsdir)
subprocess.call(['zip',files1,files])
三、time模块
python中,通常用这几种方式来表示时间,时间戳
格式化的时间字符串
元组
下面是python time模块几个函数的作用:
四、argparse模块
是用于命令项选项与参数解析的模块,
argparse 使用分为三步:创建 ArgumentParser() 对象
调用 add_argument() 方法添加参数
使用 parse_args() 解析添加的参数
1、创建解析器
parser = argparse.ArgumentParser()
2、添加位置参数
声明的参数名前缀不带‘-’或‘—’,按照顺序进行解析,在命令中必须出现
parser.add_argument("country")
3、添加可选参数
声明的参数名前缀带‘-’或‘—’,前缀是’-‘的为短参数,前缀是’—‘是长参数,两者可以都有,也可以只有一个,短参数和长参数效果一样
parser.add_argument("-a",“--attribute”)
4、参数解析
args = parser.parse_args()
5、调用解析参数
print "Country:",args.country
if args.attribute:
print "Attribute:",args.attribute
6、添加参数说明
在定义每个参数的时候加入help = “xxxx”属性,这样就会在帮助文档中显示出该参数的用法或意义
parser.add_argument("country",help="input school's country ")
7、添加程序说明
对于程序的说明需要在定义解析器的时候使用description属性
parser = argparse.ArgumentParser(description="input your school information")
8、指定参数类型
指定type=int属性
parser.add_argument("-n",type=int)
9、指定参数个数
指定nargs=‘+’,
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
10、参数默认值
调用default属性,可以给参数一个默认的值
parser.add_argument("-n",type=int,default=1)
示例:
import shutil
import sys
import time
import os
import argparse
usage = 'python move_files_over_x_days.py -src [SRC] -dst [DST] -days [DAYS]'
description = 'Move files from src to dst if they are older than a certain number of days. Default is 240 days'
args_parser = argparse.ArgumentParser(usage=usage, description=description)
args_parser.add_argument('-src', '--src', type=str, nargs='?', default='.', help='(OPTIONAL) Directory where files will be moved from. Defaults to current directory')
args_parser.add_argument('-dst', '--dst', type=str, nargs='?', required=True, help='(REQUIRED) Directory where files will be moved to.')
args_parser.add_argument('-days', '--days', type=int, nargs='?', default=240, help='(OPTIONAL) Days value specifies the minimum age of files to be moved. Default is 240.')
args = args_parser.parse_args()
if args.days < 0:
args.days = 0
src = args.src
dst = args.dst
days = args.days
now = time.time()
if not os.path.exists(dst):
os.mkdir(dst)
for f in os.listdir(src):
f = src + '/' + f
if os.stat(f).st_mtime < now - days * 86400:
if os.path.isfile(f):
shutil.move(f, dst)
五、platform模块
模块用来获得操作系统, 系统架构, python信息等
操作系统相关system() : 操作系统类型(见例)
version(): 操作系统版本
release(): 操作系统发布号, 例如win 7返回7, 还有如NT, 2.2.0之类.
platform(aliased=0, terse=0): 操作系统信息字符串,扥与system()+win32_ver()[:3]
win32_ver(release=’’, version=’’, csd=’’, ptype=’’): win系统相关信息
linux_distribution(distname=’’, version=’’, id=’’, supported_dists=(‘SuSE’, ‘debiaare’, ‘yellowdog’, ‘gentoo’, ‘UnitedLinux’, ‘turbolinux’), full_distribution_name=1): Linux系统相关信息
dist(distname=’’, version=’’, id=’’, supported_dists=(‘SuSE’, ‘debian’, ‘fedora’, ‘redhat’, ‘centos’, ‘mandrake’, ‘mandriva’, ‘rocks’, ‘slackware’, ‘yellowdog’, ‘gentoo’, ‘UnitedLinux’, ‘turbolinux’)): 尝试获取Linux OS发布版本信息.返回(distname,version,id). dist是发布版本的意思.
mac_ver(release=’’, versioninfo=(‘’, ‘’, ‘’), machine=’’): mac版本
java_ver(release=’’, vendor=’’, vminfo=(‘’, ‘’, ‘’), osinfo=(‘’, ‘’, ‘’)): java版本
libc_ver(executable=r’c:\Python27\python.exe’, lib=’’, version=’’, chunksize=2048): libc版本,linux相关吧.
系统信息uname(): 返回元组,system, node, release, version, machine, processor.
architecture(executable=r’c:\Python27\python.exe’, bits=’’, linkage=’’): 系统架构
machine() : CPU平台,AMD,x86?(见例)
node() : 节点名(机器名,如Hom-T400)
processor() : CPU信息
system_alias(system, release, version): 返回相应元组..
python相关python_version(): py版本号
python_branch(): python分支(子版本信息),一般为空.
python_build(): python编译号(default)和日期.
python_compiler(): py编译器信息
python_implementation(): python安装履行方式,如CPython, Jython, Pypy, IronPython(.net)等.
python_revision(): python类型修改版信息,一般为空.
python_version_tuple():python版本号分割后的tuple.
popen(cmd, mode=’r’, bufsize=None): portable popen() 接口,执行各种命令.
import platform as pl
profile = [
'architecture',
'linux_distribution',
'mac_ver',
'machine',
'node',
'platform',
'processor',
'python_build',
'python_compiler',
'python_version',
'release',
'system',
'uname',
'version',
]
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
for key in profile:
if hasattr(pl, key):
print(key + bcolors.BOLD + ": " + str(getattr(pl, key)()) + bcolors.ENDC)
模块实战:https://github.com/jasonliuxyz/develop/tree/master/everydaygithub.com