python代码命令行tab补齐_python 脚本交互输入系统命令时实现Tab补全

command_tab.py

#/usr/bin/python

#coding:utf8

import readline,os,commands,sys

readline.set_completer_delims(' \t\n`~!@#$%^&*()=+[{]}\\|;:\'",<>/?')

def allcommands():

a=commands.getoutput("PATH=$PATH:./:/usr/lib:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:;for c in $(echo $PATH |sed 's/:/ /g');do ls $c;done")

return a.strip().split('\n')

def alllocalpath(path=''):

result = []

if not path: path = '.'

for f in os.listdir(path):

qf = os.path.join(path,f)

if os.path.isdir(qf):

result.append(f+os.sep)

else:

result.append(f)

return result

class BufferAwareCompleter(object):

def __init__(self, custcmd, allcmd):

self.options = custcmd

self.current_candidates = []

self.allcmd = allcmd

return

def complete(self, text, state):

response = None

if state == 0:

origline = readline.get_line_buffer()

begin = readline.get_begidx()

end = readline.get_endidx()

being_completed = origline[begin:end]

words = origline.split()

if not words:

self.current_candidates = sorted(self.options)

else:

try:

if begin == 0:

candidates = self.allcmd

else:

if origline.endswith(' '):words.append('')

basedir,basefile = os.path.split(words[-1])

candidates = alllocalpath(basedir)

being_completed = basefile

if being_completed:

self.current_candidates = [ w for w in candidates

if w.startswith(being_completed) ]

else:

self.current_candidates = candidates

except (KeyError, IndexError), err:

self.current_candidates = []

try:

response = self.current_candidates[state]

except IndexError:

response = None

return response

custcmd = ['exit','quit']

allcmd = custcmd[:]

allcmd.extend(allcommands())

readline.set_completer(BufferAwareCompleter(custcmd,allcmd).complete)

readline.parse_and_bind('tab: complete')

import command_tab

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值