腳本編程與系統管理
通過重定向/管道/文件接受輸入
- 使用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