Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Python 腳本入門實例:命令列參數、函數拆分、條件判斷與退出碼

第一次照著需求寫腳本,最容易犯的錯不是語法,而是把整件事塞進一坨沒有結構的程式碼裡。這個例子是一個通用的資料格式轉換工具:來源檔案裡只有幾個欄位有值,目標格式卻要求固定欄位數,缺的地方補 0。順便把命令列參數解析、函數拆分、判斷與退出碼這幾件事一起練一次。

需求拆解

來源資料:以某個分隔符切開的若干欄位。目標資料:指定欄位數,把來源欄位填到指定位置,其餘欄位填 0。技術點集中在 getopt 參數解析與檔案讀寫。

程式碼

#!/usr/bin/python
# -*- coding: utf-8 -*-
# dataformat.py:把來源資料轉成目標欄位格式

import os, getopt, sys

# 讀檔,回傳所有行
def read_file(path):
    f = open(path, "r")
    lines = f.readlines()
    f.close()
    return lines

# 處理單行:依 to 指定的位置填入來源欄位,其餘補 0
def one_line_proc(parts, total, to, outsp):
    toindex = 0
    outline = ""
    for i in range(1, total + 1):
        if toindex != len(to) and i == to[toindex]:
            outline += parts[toindex]
            toindex += 1
        else:
            outline += "0"
        if i != total:
            outline += outsp
    return outline

# 從 inpath 讀到 outpath
def process(inpath, total, to, outpath, insp="\t", outsp="\t"):
    lines = read_file(inpath)
    f = open(outpath, "w")
    result = []
    for line in lines:
        parts = line.strip("\n").split(insp)
        if len(parts) == len(to):
            result.append(one_line_proc(parts, total, to, outsp) + "\n")
    f.writelines(result)
    f.close()

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "F:P:t:a:i:o:")
        if not len(opts) >= 3:
            print("the mount of params must great equal than 3")
            sys.exit(1)
        for op, value in opts:
            if op == "-i":
                inpath = value
            elif op == "-o":
                outpath = value
            elif op == "-t":
                total = int(value)
            elif op == "-a":
                to = value.split(",")
            elif op == "-F":
                insp = value.decode("string_escape")
            elif op == "-P":
                outsp = value.decode("string_escape")
    except getopt.GetoptError:
        print("params are not defined well!")

    if 'outpath' not in dir():
        outpath = inpath + ".dist"
    if 'inpath' not in dir():
        print("-i param is needed, input file path must define!")
        sys.exit(1)
    if 'total' not in dir():
        print("-t param is needed, the fields of result file must define!")
        sys.exit(1)
    if 'to' not in dir():
        print("-a param is needed, must assign the field to put !")
        sys.exit(1)
    if not os.path.exists(inpath):
        print("file : %s is not exists" % inpath)
        sys.exit(1)

    tmp = []
    for st in to:
        tmp.append(int(st))
    to = tmp

    if 'insp' in dir() and 'outsp' in dir():
        process(inpath, total, to, outpath, insp, outsp)
    elif 'insp' in dir():
        process(inpath, total, to, outpath, insp)
    elif 'outsp' in dir():
        process(inpath, total, to, outpath, outsp=outsp)
    else:
        process(inpath, total, to, outpath)

main()

幾個值得記住的寫法

參數不足就印訊息並 sys.exit(1),讓呼叫端能靠退出碼判斷成敗;輸出檔沒給就自動用「輸入檔名 + .dist」,減少一次手忙腳亂;用 dir() 判斷變數是否被赋值,是舊版 Python 常見的土法子,今天用 argparse 會乾淨得多,但邏輯骨架是一樣的。

另外,one_line_proc 裡「位置對得上就填值、對不上就補 0」的設計,讓這支腳本可以套用到任何「欄位稀疏」的資料上,這也是它比一次性腳本耐用的原因。

Copyright © Linux教程網 All Rights Reserved