UNIXコマンドしりとり in Python

h:keyword:UNIXコマンドしりとりなんてのがはじまってたので、Pythonでこんなのつくってみた。別にヒマなわけではない。

#!/usr/bin/python

import os
import stat
import optparse
import random

def main():
  defaultdir = [
    "/bin",
    "/sbin",
    "/usr/bin",
    "/usr/sbin"
  ]
  parser = optparse.OptionParser()
  parser.add_option("-d", "--dir", dest="directories", action="append",
    type="string", default = defaultdir)
  (options, args) = parser.parse_args()

  headdict = {}
  for directory in options.directories:
    for command in listcommand(directory):
      head = command[0]
      if headdict.has_key(head):
        tmp = headdict[head]
        tmp.append(command)
      else:
        headdict[head] = [command]
  firstlist = headdict[random.choice(headdict.keys())]
  candidate = random.choice(firstlist)
  firstlist.remove(candidate)
  print candidate
  while candidate != '':
    candidate = capping(headdict, candidate)
    print candidate

def listcommand(directory) :
  if os.access(directory, os.F_OK | os.R_OK | os.X_OK) and stat.S_ISDIR(os.stat(directory)[stat.ST_MODE]):
    return os.listdir(directory)

def capping(headdict, before):
  tail = before[-1]
  if not headdict.has_key(tail) :
    return '' 
  nextlist = headdict[tail]
  listlength = len(nextlist)
  if listlength == 0 :
    return ''
  nextcommand = random.choice(nextlist)
  nextlist.remove(nextcommand)
  return nextcommand

if __name__ == "__main__":
	main()

一応解説すると、UNIXのコマンドが入ってそうなディレクトリのファイル名をつかって、自動でしりとりをやる。ちゃんと実行可能かどうか見たほうがいいかな?