python_cookbook记录

脚本编程与系统管理

2017-09-21  本文已影响0人  buildbody_coder

脚本编程与系统管理

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

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!')

解析命令行选项

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)

执行外部命令并获取输出

import subprocess
try:
    out_bytes = subprocess.check_output(['cd', 'arg2'])
except subprocess.CalledProcessError as e:
    out_bytes = e.output
    code = e.returncode
    print (code)
out_bytes = subprocess.check_output('ls', shell=True)
print (out_bytes.decode('utf8'))
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 复制文件

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')

通过文件名查找文件

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)

简单脚本增加日志功能

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
上一篇下一篇

猜你喜欢

热点阅读