chap07/kadai3.py

サンプルコードのダウンロード

 1#!/usr/bin/env python
 2# -*- coding: utf-8 -*-
 3
 4import os
 5import sys
 6import datetime
 7import argparse
 8
 9
10def parse_args():
11    parser = argparse.ArgumentParser(description='Simple emulation of ls command')
12    parser.add_argument('-S', action='store_true', default=False,
13                        help='sort in size')
14    parser.add_argument('-r', action='store_true', default=False,
15                        help='reverse sort order')
16    args = parser.parse_args()
17
18    # ソートキー
19    if args.S:
20        key = 'size'
21    else:
22        key = 'name'
23
24    # ソートオーダー
25    reverse = args.r
26
27    return key, reverse
28
29def myls(dirname, key=None, reverse=False):
30    if key is None:
31        key == 'name'
32
33    # ファイルリストと属性値を取得
34    files = list()
35    with os.scandir(dirname) as it:
36        for entry in it:
37            name = entry.name
38            stat = entry.stat()
39            files.append(dict(name=name,
40                              size=stat.st_size,
41                              time=stat.st_mtime))
42
43    # ソート
44    if key == 'name':
45        files.sort(key=lambda x: x['name'], reverse=False ^ reverse)
46    elif key == 'size':
47        files.sort(key=lambda x: x['size'], reverse=True ^ reverse)
48    elif key == 'time':
49        files.sort(key=lambda x: x['time'], reverse=True ^ reverse)
50    else:
51        raise ValueError('Error: Invaid sort key: {}'.format(key))
52
53    # フォーマットして出力
54    for f in files:
55        t = datetime.datetime.fromtimestamp(f['time'])
56        f['timestr'] = t.ctime()
57        print('{size:8d} {timestr} {name}'.format(**f))
58
59
60if __name__ == '__main__':
61    key, reverse = parse_args()
62    myls('.', key, reverse)