def create_argparser(self, command):
try:
argparse_args = getattr(self, "argparse_" + command)
except AttributeError:
return None
doc_lines = getattr(self, "do_" + command).__doc__.expandtabs().splitlines()
if '' in doc_lines:
blank_idx = doc_lines.index('')
usage = doc_lines[:blank_idx]
description = doc_lines[blank_idx+1:]
else:
usage = doc_lines
description = []
parser = argparse.ArgumentParser(
prog=command,
usage='\n'.join(usage),
description='\n'.join(description)
)
for args, kwargs in argparse_args:
parser.add_argument(*args, **kwargs)
return parser
python类__doc__()的实例源码
def do_help(self, line):
"""help [COMMAND]
List available commands with no arguments, or detailed help when
a command is provided.
"""
# We provide a help function so that we can trim the leading spaces
# from the docstrings. The builtin help function doesn't do that.
if not line:
cmd.Cmd.do_help(self, line)
self.print("Use Control-D to exit rshell.")
return
parser = self.create_argparser(line)
if parser:
parser.print_help()
return
try:
doc = getattr(self, 'do_' + line).__doc__
if doc:
self.print("%s" % trim(doc))
return
except AttributeError:
pass
self.print(str(self.nohelp % (line,)))
def init_history(self, histfile):
#readline.parse_and_bind("bind ^I rl_complete")
# Register our completer function
readline.set_completer(SimpleCompleter(G.cmmands.keys()).complete)
#readline.set_completer(TabCompleter().complete)
### Add autocompletion
if 'libedit' in readline.__doc__:
readline.parse_and_bind("bind -e")
readline.parse_and_bind("bind '\t' rl_complete")
else:
readline.parse_and_bind("tab: complete")
# Use the tab key for completion
#readline.parse_and_bind('tab: complete')
if hasattr(readline, "read_history_file"):
try:
readline.read_history_file(histfile)
except:
pass
atexit.register(self.save_history, histfile)
def __enter__(self):
self._original_completer = readline.get_completer()
self._original_delims = readline.get_completer_delims()
readline.set_completer(self.complete)
readline.set_completer_delims(' \t\n;')
# readline can be implemented using GNU readline or libedit
# which have different configuration syntax
if 'libedit' in readline.__doc__:
readline.parse_and_bind('bind ^I rl_complete')
else:
readline.parse_and_bind('tab: complete')
def test_context_manager_libedit(self, mock_readline):
mock_readline.__doc__ = 'libedit'
self._test_context_manager_with_mock_readline(mock_readline)
def test_context_manager_readline(self, mock_readline):
mock_readline.__doc__ = 'GNU readline'
self._test_context_manager_with_mock_readline(mock_readline)
def enable_tab_completion(unused_command):
"""Enables readline tab completion using the system specific syntax."""
libedit = 'libedit' in readline.__doc__
command = 'bind ^I rl_complete' if libedit else 'tab: complete'
readline.parse_and_bind(command)
def choice():
global name
global module
try:
if module == "":
readline.set_completer(completer)
readline.set_completer_delims('')
if 'libedit' in readline.__doc__:
readline.parse_and_bind("bind ^I rl_complete")
else:
readline.parse_and_bind("tab: complete")
raw_choice = raw_input(" >> [" + name + "]# ")
choice = raw_choice
exec_menu(choice)
else:
readline.set_completer(completer)
readline.set_completer_delims('')
if 'libedit' in readline.__doc__:
readline.parse_and_bind("bind ^I rl_complete")
else:
readline.parse_and_bind("tab: complete")
raw_choice = raw_input(" >> [" + name + "][" + module + "]# ")
choice = raw_choice
exec_menu(choice)
except EOFError:
pass
except KeyboardInterrupt:
exec_menu('exit')
def __enter__(self):
self._original_completer = readline.get_completer()
self._original_delims = readline.get_completer_delims()
readline.set_completer(self.complete)
readline.set_completer_delims(' \t\n;')
# readline can be implemented using GNU readline or libedit
# which have different configuration syntax
if 'libedit' in readline.__doc__:
readline.parse_and_bind('bind ^I rl_complete')
else:
readline.parse_and_bind('tab: complete')
def test_context_manager_libedit(self, mock_readline):
mock_readline.__doc__ = 'libedit'
self._test_context_manager_with_mock_readline(mock_readline)
def test_context_manager_readline(self, mock_readline):
mock_readline.__doc__ = 'GNU readline'
self._test_context_manager_with_mock_readline(mock_readline)
def enable_tab_completion(unused_command):
"""Enables readline tab completion using the system specific syntax."""
libedit = 'libedit' in readline.__doc__
command = 'bind ^I rl_complete' if libedit else 'tab: complete'
readline.parse_and_bind(command)
def launch_ui(args):
# Setup tab completion
try:
import readline
except ImportError:
print('%s[!] Module \'readline\' not available. Tab complete disabled.%s' % (Colors.R, Colors.N))
else:
import rlcompleter
if 'libedit' in readline.__doc__:
readline.parse_and_bind('bind ^I rl_complete')
else:
readline.parse_and_bind('tab: complete')
readline.set_completer_delims(re.sub('[/-]', '', readline.get_completer_delims()))
# Instantiate the UI object
x = cli.CLI(cli.Mode.CONSOLE)
# check for and run version check
if args.check:
if not x.version_check(): return
# Check for and run script session
if args.script_file:
x.do_resource(args.script_file)
# Run the UI
try:
x.cmdloop()
except KeyboardInterrupt:
print('')
# ======================================================================================================================
# MAIN
# ======================================================================================================================
def setup_readline():
"""Sets up the readline module and completion supression, if available."""
global RL_COMPLETION_SUPPRESS_APPEND, RL_LIB, RL_CAN_RESIZE
if RL_COMPLETION_SUPPRESS_APPEND is not None:
return
try:
import readline
except ImportError:
return
import ctypes
import ctypes.util
readline.set_completer_delims(' \t\n')
if not readline.__file__.endswith('.py'):
RL_LIB = lib = ctypes.cdll.LoadLibrary(readline.__file__)
try:
RL_COMPLETION_SUPPRESS_APPEND = ctypes.c_int.in_dll(
lib, 'rl_completion_suppress_append')
except ValueError:
# not all versions of readline have this symbol, ie Macs sometimes
RL_COMPLETION_SUPPRESS_APPEND = None
RL_CAN_RESIZE = hasattr(lib, 'rl_reset_screen_size')
env = builtins.__xonsh_env__
# reads in history
readline.set_history_length(-1)
ReadlineHistoryAdder()
# sets up IPython-like history matching with up and down
readline.parse_and_bind('"\e[B": history-search-forward')
readline.parse_and_bind('"\e[A": history-search-backward')
# Setup Shift-Tab to indent
readline.parse_and_bind('"\e[Z": "{0}"'.format(env.get('INDENT')))
# handle tab completion differences found in libedit readline compatibility
# as discussed at http://stackoverflow.com/a/7116997
if readline.__doc__ and 'libedit' in readline.__doc__:
readline.parse_and_bind("bind ^I rl_complete")
else:
readline.parse_and_bind("tab: complete")
def __init__(self, stream_desc, nodeid, *_a, **kw):
self.nodeid = kw.get('nodeid', '1')
self.tun_if = None
self.wpan_api = WpanApi(stream_desc, nodeid)
self.wpan_api.queue_register(SPINEL.HEADER_DEFAULT)
self.wpan_api.callback_register(SPINEL.PROP_STREAM_NET,
self.wpan_callback)
Cmd.__init__(self)
Cmd.identchars = string.ascii_letters + string.digits + '-'
if sys.stdin.isatty():
self.prompt = MASTER_PROMPT + " > "
else:
self.use_rawinput = 0
self.prompt = ""
SpinelCliCmd.command_names.sort()
self.history_filename = os.path.expanduser("~/.spinel-cli-history")
try:
import readline
try:
readline.read_history_file(self.history_filename)
except IOError:
pass
except ImportError:
print("Module readline unavailable")
else:
import rlcompleter
if 'libedit' in readline.__doc__:
readline.parse_and_bind('bind ^I rl_complete')
else:
readline.parse_and_bind('tab: complete')
self.prop_set_value(SPINEL.PROP_IPv6_ICMP_PING_OFFLOAD, 1)
self.prop_set_value(SPINEL.PROP_THREAD_RLOC16_DEBUG_PASSTHRU, 1)
def do_help(self, line):
if line:
cmd, _arg, _unused = self.parseline(line)
try:
doc = getattr(self, 'do_' + cmd).__doc__
except AttributeError:
doc = None
if doc:
self.log("%s\n" % textwrap.dedent(doc))
else:
self.log("No help on %s\n" % (line))
else:
self.print_topics(
"\nAvailable commands (type help <name> for more information):",
SpinelCliCmd.command_names, 15, 80)
def init_env(self):
if 'libedit' in readline.__doc__:
readline.parse_and_bind("bind ^I rl_complete")
else:
readline.parse_and_bind("tab: complete")