本文整理匯總了Python中cmd2.Cmd方法的典型用法代碼示例。如果您正苦於以下問題:Python cmd2.Cmd方法的具體用法?Python cmd2.Cmd怎麽用?Python cmd2.Cmd使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類cmd2
的用法示例。
在下文中一共展示了cmd2.Cmd方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: setup_cmd2
# 需要導入模塊: import cmd2 [as 別名]
# 或者: from cmd2 import Cmd [as 別名]
def setup_cmd2(self, hist_file):
""""Set up interactive command line interface."""
# delete unused commands that are baked-into cmd2 and set some options
del cmd2.Cmd.do_py
del cmd2.Cmd.do_edit
del cmd2.Cmd.do_shortcuts
del cmd2.Cmd.do_pyscript
del cmd2.Cmd.do_set
del cmd2.Cmd.do_alias
del cmd2.Cmd.do_load
cmd2.Cmd.abbrev = True
self.allow_cli_args = False # disable parsing of command-line args by cmd2
self.allow_redirection = False # disable redirection to enable right shift (>>) in custom_hash to work
self.redirector = '\xff' # disable redirection in the parser as well
self.shortcuts.update({'sh': 'show'}) # don't want "sh" to trigger the hidden "shell" command
# init cmd2 and the history file
cmd2.Cmd.__init__(self, persistent_history_file=hist_file, persistent_history_length=200)
# disable help on builtins
self.hidden_commands.append('shell')
self.hidden_commands.append('exit')
示例2: __init__
# 需要導入模塊: import cmd2 [as 別名]
# 或者: from cmd2 import Cmd [as 別名]
def __init__(self):
# Add dynamic commands before calling cmd2.Cmd's init since it validates command names
for command in COMMAND_LIST:
# Create command function and add help category to it
cmd_func = functools.partial(self.send_text, text=command)
cmd2.categorize(cmd_func, CATEGORY)
# Add command function to CLI object
cmd_func_name = COMMAND_FUNC_PREFIX + command
setattr(self, cmd_func_name, cmd_func)
# Add help function to CLI object
help_func = functools.partial(self.text_help, text=command)
help_func_name = HELP_FUNC_PREFIX + command
setattr(self, help_func_name, help_func)
super().__init__(use_ipython=True)
示例3: test_transcript
# 需要導入模塊: import cmd2 [as 別名]
# 或者: from cmd2 import Cmd [as 別名]
def test_transcript(request, capsys, filename, feedback_to_output):
# Get location of the transcript
test_dir = os.path.dirname(request.module.__file__)
transcript_file = os.path.join(test_dir, 'transcripts', filename)
# Need to patch sys.argv so cmd2 doesn't think it was called with
# arguments equal to the py.test args
testargs = ['prog', '-t', transcript_file]
with mock.patch.object(sys, 'argv', testargs):
# Create a cmd2.Cmd() instance and make sure basic settings are
# like we want for test
app = CmdLineApp()
app.feedback_to_output = feedback_to_output
# Run the command loop
sys_exit_code = app.cmdloop()
assert sys_exit_code == 0
# Check for the unittest "OK" condition for the 1 test which ran
expected_start = ".\n----------------------------------------------------------------------\nRan 1 test in"
expected_end = "s\n\nOK\n"
_, err = capsys.readouterr()
assert err.startswith(expected_start)
assert err.endswith(expected_end)
示例4: test_history_transcript_bad_filename
# 需要導入模塊: import cmd2 [as 別名]
# 或者: from cmd2 import Cmd [as 別名]
def test_history_transcript_bad_filename():
app = CmdLineApp()
app.stdout = StdSim(app.stdout)
run_cmd(app, 'orate this is\na /multiline/\ncommand;\n')
run_cmd(app, 'speak /tmp/file.txt is not a regex')
expected = r"""(Cmd) orate this is
> a /multiline/
> command;
this is a \/multiline\/ command
(Cmd) speak /tmp/file.txt is not a regex
\/tmp\/file.txt is not a regex
"""
# make a tmp file
history_fname = '~/fakedir/this_does_not_exist.txt'
# tell the history command to create a transcript
run_cmd(app, 'history -t "{}"'.format(history_fname))
# read in the transcript created by the history command
with pytest.raises(FileNotFoundError):
with open(history_fname) as f:
transcript = f.read()
assert transcript == expected
示例5: test_run_script_record_transcript
# 需要導入模塊: import cmd2 [as 別名]
# 或者: from cmd2 import Cmd [as 別名]
def test_run_script_record_transcript(base_app, request):
test_dir = os.path.dirname(request.module.__file__)
filename = os.path.join(test_dir, 'scripts', 'help.txt')
assert base_app._script_dir == []
assert base_app._current_script_dir is None
# make a tmp file to use as a transcript
fd, transcript_fname = tempfile.mkstemp(prefix='', suffix='.trn')
os.close(fd)
# Execute the run_script command with the -t option to generate a transcript
run_cmd(base_app, 'run_script {} -t {}'.format(filename, transcript_fname))
assert base_app._script_dir == []
assert base_app._current_script_dir is None
# read in the transcript created by the history command
with open(transcript_fname) as f:
xscript = f.read()
assert xscript.startswith('(Cmd) help -v\n')
verify_help_text(base_app, xscript)
示例6: test_transcript_failure
# 需要導入模塊: import cmd2 [as 別名]
# 或者: from cmd2 import Cmd [as 別名]
def test_transcript_failure(request, capsys):
# Get location of the transcript
test_dir = os.path.dirname(request.module.__file__)
transcript_file = os.path.join(test_dir, 'transcripts', 'failure.txt')
# Need to patch sys.argv so cmd2 doesn't think it was called with
# arguments equal to the py.test args
testargs = ['prog', '-t', transcript_file]
with mock.patch.object(sys, 'argv', testargs):
# Create a cmd2.Cmd() instance and make sure basic settings are
# like we want for test
app = CmdLineApp()
app.feedback_to_output = False
# Run the command loop
sys_exit_code = app.cmdloop()
assert sys_exit_code != 0
expected_start = "File "
expected_end = "s\n\nFAILED (failures=1)\n\n"
_, err = capsys.readouterr()
assert err.startswith(expected_start)
assert err.endswith(expected_end)
示例7: test_ansi_prompt_escaped
# 需要導入模塊: import cmd2 [as 別名]
# 或者: from cmd2 import Cmd [as 別名]
def test_ansi_prompt_escaped():
from cmd2.rl_utils import rl_make_safe_prompt
app = cmd2.Cmd()
color = 'cyan'
prompt = 'InColor'
color_prompt = ansi.style(prompt, fg=color)
readline_hack_start = "\x01"
readline_hack_end = "\x02"
readline_safe_prompt = rl_make_safe_prompt(color_prompt)
assert prompt != color_prompt
if sys.platform.startswith('win'):
# PyReadline on Windows doesn't suffer from the GNU readline bug which requires the hack
assert readline_safe_prompt.startswith(ansi.fg_lookup(color))
assert readline_safe_prompt.endswith(ansi.FG_RESET)
else:
assert readline_safe_prompt.startswith(readline_hack_start + ansi.fg_lookup(color) + readline_hack_end)
assert readline_safe_prompt.endswith(readline_hack_start + ansi.FG_RESET + readline_hack_end)
示例8: test_select_options
# 需要導入模塊: import cmd2 [as 別名]
# 或者: from cmd2 import Cmd [as 別名]
def test_select_options(select_app, monkeypatch):
# Mock out the read_input call so we don't actually wait for a user's response on stdin
read_input_mock = mock.MagicMock(name='read_input', return_value='2')
monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
food = 'bacon'
out, err = run_cmd(select_app, "eat {}".format(food))
expected = normalize("""
1. sweet
2. salty
{} with salty sauce, yum!
""".format(food))
# Make sure our mock was called with the expected arguments
read_input_mock.assert_called_once_with('Sauce? ')
# And verify the expected output to stdout
assert out == expected
示例9: test_select_invalid_option_too_big
# 需要導入模塊: import cmd2 [as 別名]
# 或者: from cmd2 import Cmd [as 別名]
def test_select_invalid_option_too_big(select_app, monkeypatch):
# Mock out the input call so we don't actually wait for a user's response on stdin
read_input_mock = mock.MagicMock(name='read_input')
# If side_effect is an iterable then each call to the mock will return the next value from the iterable.
read_input_mock.side_effect = ['3', '1'] # First pass an invalid selection, then pass a valid one
monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
food = 'fish'
out, err = run_cmd(select_app, "eat {}".format(food))
expected = normalize("""
1. sweet
2. salty
'3' isn't a valid choice. Pick a number between 1 and 2:
{} with sweet sauce, yum!
""".format(food))
# Make sure our mock was called exactly twice with the expected arguments
arg = 'Sauce? '
calls = [mock.call(arg), mock.call(arg)]
read_input_mock.assert_has_calls(calls)
assert read_input_mock.call_count == 2
# And verify the expected output to stdout
assert out == expected
示例10: test_select_list_of_strings
# 需要導入模塊: import cmd2 [as 別名]
# 或者: from cmd2 import Cmd [as 別名]
def test_select_list_of_strings(select_app, monkeypatch):
# Mock out the input call so we don't actually wait for a user's response on stdin
read_input_mock = mock.MagicMock(name='read_input', return_value='2')
monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
out, err = run_cmd(select_app, "study")
expected = normalize("""
1. math
2. science
Good luck learning {}!
""".format('science'))
# Make sure our mock was called with the expected arguments
read_input_mock.assert_called_once_with('Subject? ')
# And verify the expected output to stdout
assert out == expected
示例11: test_select_list_of_tuples
# 需要導入模塊: import cmd2 [as 別名]
# 或者: from cmd2 import Cmd [as 別名]
def test_select_list_of_tuples(select_app, monkeypatch):
# Mock out the input call so we don't actually wait for a user's response on stdin
read_input_mock = mock.MagicMock(name='read_input', return_value='2')
monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
out, err = run_cmd(select_app, "procrastinate")
expected = normalize("""
1. Netflix
2. WebSurfing
Have fun procrasinating with {}!
""".format('YouTube'))
# Make sure our mock was called with the expected arguments
read_input_mock.assert_called_once_with('How would you like to procrastinate? ')
# And verify the expected output to stdout
assert out == expected
示例12: test_select_uneven_list_of_tuples
# 需要導入模塊: import cmd2 [as 別名]
# 或者: from cmd2 import Cmd [as 別名]
def test_select_uneven_list_of_tuples(select_app, monkeypatch):
# Mock out the input call so we don't actually wait for a user's response on stdin
read_input_mock = mock.MagicMock(name='read_input', return_value='2')
monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
out, err = run_cmd(select_app, "play")
expected = normalize("""
1. Electric Guitar
2. Drums
Charm us with the {}...
""".format('Drums'))
# Make sure our mock was called with the expected arguments
read_input_mock.assert_called_once_with('Instrument? ')
# And verify the expected output to stdout
assert out == expected
示例13: test_get_help_topics_hidden
# 需要導入模塊: import cmd2 [as 別名]
# 或者: from cmd2 import Cmd [as 別名]
def test_get_help_topics_hidden():
# Verify get_help_topics() filters out hidden commands
class TestApp(cmd2.Cmd):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def do_my_cmd(self, args):
pass
def help_my_cmd(self, args):
pass
app = TestApp()
assert 'my_cmd' in app.get_help_topics()
app.hidden_commands.append('my_cmd')
assert 'my_cmd' not in app.get_help_topics()
示例14: test_default_sort_key
# 需要導入模塊: import cmd2 [as 別名]
# 或者: from cmd2 import Cmd [as 別名]
def test_default_sort_key(cmd2_app):
text = ''
line = 'test_sort_key {}'.format(text)
endidx = len(line)
begidx = endidx - len(text)
# First do alphabetical sorting
cmd2_app.default_sort_key = cmd2.Cmd.ALPHABETICAL_SORT_KEY
expected = ['1', '11', '2']
first_match = complete_tester(text, line, begidx, endidx, cmd2_app)
assert first_match is not None and cmd2_app.completion_matches == expected
# Now switch to natural sorting
cmd2_app.default_sort_key = cmd2.Cmd.NATURAL_SORT_KEY
expected = ['1', '2', '11']
first_match = complete_tester(text, line, begidx, endidx, cmd2_app)
assert first_match is not None and cmd2_app.completion_matches == expected
示例15: test_history_edit
# 需要導入模塊: import cmd2 [as 別名]
# 或者: from cmd2 import Cmd [as 別名]
def test_history_edit(monkeypatch):
app = cmd2.Cmd(multiline_commands=['alias'])
# Set a fake editor just to make sure we have one. We aren't really
# going to call it due to the mock
app.editor = 'fooedit'
# Mock out the _run_editor call so we don't actually open an editor
edit_mock = mock.MagicMock(name='_run_editor')
monkeypatch.setattr("cmd2.Cmd._run_editor", edit_mock)
# Mock out the run_script call since the mocked edit won't produce a file
run_script_mock = mock.MagicMock(name='do_run_script')
monkeypatch.setattr("cmd2.Cmd.do_run_script", run_script_mock)
# Put commands in history
run_cmd(app, 'help')
run_cmd(app, 'alias create my_alias history;')
run_cmd(app, 'history -e 1:2')
# Make sure both functions were called
edit_mock.assert_called_once()
run_script_mock.assert_called_once()