ikautak.log

C/C++, Python, CUDA, Android, Linux kernel, Network, etc.

python cmdモジュールの補完機能

pythonのcmdモジュールで、ファイル名の補完機能を付ける方法。 cmdモジュールは簡単にCUIのアプリが作れるし、コマンドの引数の補完機能を追加するのも簡単だ。

#!/usr/bin/env python
import cmd
import dircache
class MyCmd(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
self.prompt = '(MyCmd)'
def do_test(self, line):
print('cmd test ' + line)
def complete_test(self, text, line, begidx, endidx):
""" auto complete of file name.
"""
line = line.split()
if len(line) < 2:
filename = ''
path = './'
else:
path = line[1]
if '/' in path:
i = path.rfind('/')
filename = path[i+1:]
path = path[:i]
else:
filename = path
path = './'
ls = dircache.listdir(path)
ls = ls[:] # for overwrite in annotate.
dircache.annotate(path, ls)
if filename == '':
return ls
else:
return [f for f in ls if f.startswith(filename)]
if __name__ == '__main__':
mycmd = MyCmd()
mycmd.cmdloop()
view raw cmd_test.py hosted with ❤ by GitHub

実行すると(MyCmd)というプロンプトが表示されてコマンド入力待ちになる。
TABキーを2回押すとコマンド候補が表示される。

(MyCmd)
help  test

testと打ってTABキーを押すと、カレントディレクトリのファイル名が候補に出てくる。
ディレクトリ名まで入力すると、そのディレクトリ内のファイルが候補に出てくる。