脚本编程与系统管理

脚本编程与系统管理

通过重定向/管道/文件接受输入

  • 使用fileinput接收python 代码的输入
  • 将python 文件变为可执行文件,可以在f_input中遍历输出
import fileinput
with fileinput.input() as f_input:
    for line in f_input:
        print (line, end='')
use:
./filein.py /etc/passwd
./filein.py < /etc/passwd

终止程序并给出错误信息

  • 标准错误打印一条消息并返回某个非零状态码来终止程序运行
raise SystemExit('It failed!')

解析命令行选项

  • 首先要创建一个 ArgumentParser实例,并使用 add_argument() 方法声明你想要支持的选项
  • dest 参数指定解析结果被指派给属性的名字
  • metavar 参数被用来生成帮助信息
  • action 参数指定跟属性对应的处理逻辑,通常的值为 store(结果存储为字符串)store_true(s设置一个默认的boolean标识)append(追加一个列表)
  • required 标志表示该参数至少要有一个。-p 和 --pat 表示两个参数名形式都可使用。
  • choices={'slow', 'fast'}, default='slow',下面的参数说明接受一个值
import argparse
parser = argparse.ArgumentParser(description='Search some files')
parser.add_argument(dest='filenames', metavar='filename', nargs='*')
parser.add_argument('-p', '--pat', metavar='pattern', required=True,
                    dest='patterns', action='append',
                    help='text pattern to search for')
parser.add_argument('-v', dest='verbose', action='store_true',
                    help='verbose mode'
                   )
parser.add_argument('-o', dest='outfile', action='store',
                    help='output file'
                   )
parser.add_argument('--speed', dest='speed', action='store',
                    choices={'slow', 'fast'}, default='slow',
                    help='search speed'
                   )
args = parser.parse_args()
print (args.filenames)
print (args.patterns)
print (args.verbose)
print (args.outfile)
print (args.speed)

命令行输入密码

import getpass
passwd = getpass.getpass()
print (passwd)

执行外部命令并获取输出

  • 使用subprocess获取标准输出的值和错误信息及其返回码
import subprocess
try:
    out_bytes = subprocess.check_output(['cd', 'arg2'])
except subprocess.CalledProcessError as e:
    out_bytes = e.output
    code = e.returncode
    print (code)
  • 通常情况下,命令不会直接执行shell,会执行shell底层的函数,传递shell=True显式的声明执行shell
out_bytes = subprocess.check_output('ls', shell=True)
print (out_bytes.decode('utf8'))
  • 使用Popen做更加复杂的操作,使用communicate需要从定向标准输出的标准输入
text = b"""
    hello world
"""
p = subprocess.Popen(
    ['wc'],
    stdout = subprocess.PIPE,
    stdin = subprocess.PIPE
)
stdout, stderr = p.communicate(text)
#转为unicode
print (stdout.decode('utf8'))

使用shutil 复制文件

  • 使用shutil复制文,并处理软连接
  • 复制过程中出现异常,回抛出到Error中
try:
    shutil.copytree(src, dst)
except shutil.Error as e:
    for src, dst, msg in e.args[0]:
        print(dst, src, msg)

创建和解压归档文件

shutil.unpack_archive('Python-3.3.0.tgz')
#第一个参数为打包的文件名字,最有一个参数为需要打包的文件夹
shutil.make_archive('py33','zip','Python-3.3.0')

通过文件名查找文件

  • 可使用 os.walk() 函数,传一个顶级目录名给它
  • os.walk() 方法为我们遍历目录树, 每次进入一个目录,它会返回一个三元组,包含相对于查找目录的相对路径,一个该目录下的目录名列表, 以及那个目录下面的文件名列表。
import os
import sys

def findfile(start, name):
    for relpath, dirs, files in os.walk(start):
        print (relpath)
        if name in files:
            full_path = os.path.join(start, relpath, name)
            print (os.path.abspath(full_path))

if __name__ == '__main__':
    findfile(sys.argv[1], sys.argv[2])

读取类型ini的配置文件

>>> from configparser import ConfigParser
>>> cfg = ConfigParser()
>>> cfg.read('config.ini')
['config.ini']
>>> cfg.sections()
['installation', 'debug', 'server']
>>> cfg.get('installation', 'library')
'/usr/local/lib'
>>> cfg.get('debug', 'log_errors')
'true'
>>> cfg.getboolean('debug', 'log_errors')
True
>>> cfg.getint('server', 'port')
8080
>>> cfg.get('server', 'signature')
'\n=================================\nBrought to you by the Python Cookbook\n===========
======================'

  • 写配置文件
et('server','port','9000')
>>> import sys
>>> cfg.write(sys.stdout)

简单脚本增加日志功能

  • 使用logging模块
  • level=logging.INFO只输出info或比其级别高的日志,filename日志会定向到文件中,默认为标准输出
  • format可以给日志加头
  • logging.getLogger().level = logging.DEBUG 可以动态的修改日志配置
import logging
def main():
    logging.basicConfig(
        filename="app.log",
        level=logging.INFO,
        format='%(levelname)s:%(asctime)s:%(message)s'
    )
    hostname = 'www.python.org'
    item = 'spam'
    filename = 'data.csv'
    mode = 'r'

    logging.critical('Host %s connection', hostname)
    logging.error("Couldn't find %r", item)
    logging.warning('Feature is deprecated')
    logging.info('Opening file %r, mode=%r', filename, mode)
    logging.debug('Got here')
if __name__ == '__main__':
    main()

打开浏览器

>>> import webbrowser
>>> c = webbrowser.get('safari')
>>> c.open('http://www.python.org')
True
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,923评论 18 139
  • Ubuntu的发音 Ubuntu,源于非洲祖鲁人和科萨人的语言,发作 oo-boon-too 的音。了解发音是有意...
    萤火虫de梦阅读 99,558评论 9 467
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,951评论 6 342
  • linux资料总章2.1 1.0写的不好抱歉 但是2.0已经改了很多 但是错误还是无法避免 以后资料会慢慢更新 大...
    数据革命阅读 12,218评论 2 33
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,264评论 25 708