Skip to content

Instantly share code, notes, and snippets.

@michitomo
Last active August 29, 2015 14:25
Show Gist options
  • Save michitomo/7fd5fd8fa57aaab88c4d to your computer and use it in GitHub Desktop.
Save michitomo/7fd5fd8fa57aaab88c4d to your computer and use it in GitHub Desktop.
Unixのlsコマンドの基本機能相当のls.pyを書いてください。コマンドライン引数で対象パス名を指定できるようにしてください。 対象パス名が省略されたときはカレントのディレクトリを対象パス名にしてください。-l,-a,-i程度のオプションは実装してください。os.system()でのlsコマンドの起動以外の実装をしてください。
import os
import argparse
import datetime
parser = argparse.ArgumentParser()
parser.add_argument('dir', nargs='?', default=".")
parser.add_argument('-a', dest="all", default=False, action="store_true")
parser.add_argument('-l', dest="list", default=False, action="store_true")
parser.add_argument('-i', dest="inode", default=False, action="store_true")
args = parser.parse_args()
files = os.listdir(args.dir)
showHidden = args.all
def isHidden(path):
return path.startswith(".")
def printLine(file):
buff = ''
stat = os.stat(file)
if args.inode:
buff = "%s\t" % (stat.st_ino)
if args.list:
buff = "%s%s %s\t%s\t%s\t%s\t%s\t" % ( buff, oct(stat.st_mode)[-3:], stat.st_nlink, stat.st_uid, stat.st_gid, stat.st_size, datetime.datetime.fromtimestamp(stat.st_mtime))
buff += file
print buff
for file in files:
if isHidden(file):
if showHidden:
printLine(file)
else:
printLine(file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment