要了解這裏發生了什麼,讓我們檢查是什麼bash函數實際上做:
COMPREPLY=($(\
COMP_LINE=$COMP_LINE COMP_POINT=$COMP_POINT \
COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD \
OPTPARSE_AUTO_COMPLETE=1 $1))
見$1
在結束了嗎?這意味着它實際上調用了我們想用特殊環境變量設置執行的Python文件!要跟蹤發生了什麼,讓我們準備一個小腳本攔截什麼optcomplete.autocomplete
做:
#!/usr/bin/env python2
import os, sys
import optparse, optcomplete
from cStringIO import StringIO
if __name__ == '__main__':
parser = optparse.OptionParser()
parser.add_option('-s', '--simple', action='store_true',
help="Simple really simple option without argument.")
parser.add_option('-o', '--output', action='store',
help="Option that requires an argument.")
opt = parser.add_option('-p', '--script', action='store',
help="Option that takes python scripts args only.")
opt.completer = optcomplete.RegexCompleter('.*\.py')
# debug env variables
sys.stderr.write("\ncalled with args: %s\n" % repr(sys.argv))
for k, v in sorted(os.environ.iteritems()):
sys.stderr.write(" %s: %s\n" % (k, v))
# setup capturing the actions of `optcomplete.autocomplete`
def fake_exit(i):
sys.stderr.write("autocomplete tried to exit with status %d\n" % i)
sys.stdout = StringIO()
sys.exit = fake_exit
# Support completion for the command-line of this script.
optcomplete.autocomplete(parser, ['.*\.tar.*'])
sys.stderr.write("autocomplete tried to write to STDOUT:\n")
sys.stderr.write(sys.stdout.getvalue())
sys.stderr.write("\n")
opts, args = parser.parse_args()
這給了我們以下的,當我們試圖自動完成它:
$ ./test.py [tab]
called with args: ['./test.py']
...
COMP_CWORD: 1
COMP_LINE: ./test.py
COMP_POINT: 10
COMP_WORDS: ./test.py
...
OPTPARSE_AUTO_COMPLETE: 1
...
autocomplete tried to exit with status 1
autocomplete tried to write to STDOUT:
-o -h -s -p --script --simple --help --output
所以optcomplete.autocomplete
只是讀取環境,準備匹配,將它們寫入STDOUT並退出。然後將結果-o -h -s -p --script --simple --help --output
放入bash數組(COMPREPLY=(...)
)並返回給bash以向用戶顯示選項。沒有魔術參與:)
'optcomplet'文檔說:「您還需要獲取Bash函數,然後告訴Bash觸發使用它的特定程序的optcomplete完成:」。如果你確實這樣做了,爲什麼你仍然在問它是如何工作的?應該很明顯,你只需要告訴bash在完成請求時要調用哪個程序。 – 2012-03-05 15:17:40
對不起,我誤解了我讀的內容。我會爲此添加一個答案。 – 2012-03-05 17:30:17