Skip to content

Commit

Permalink
Merge pull request #45 from python-cmd2/disable_redirection
Browse files Browse the repository at this point in the history
Added member boolean flag to disable output redirection and piping.
  • Loading branch information
tleonhardt committed Feb 16, 2017
2 parents 9b8bc42 + d55a618 commit 49059cb
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 14 deletions.
22 changes: 12 additions & 10 deletions cmd2.py
Original file line number Diff line number Diff line change
Expand Up @@ -502,7 +502,8 @@ class Cmd(cmd.Cmd):
# Attributes which are NOT dynamically settable at runtime
_STOP_AND_EXIT = True # distinguish end of script file from actual exit
_STOP_SCRIPT_NO_EXIT = -999
allow_cli_args = True
allow_cli_args = True # Should arguments passed on the command-line be processed as commands?
allow_redirection = True # Should output redirection and pipes be allowed
blankLinesAllowed = False
colorcodes = {'bold': {True: '\x1b[1m', False: '\x1b[22m'},
'cyan': {True: '\x1b[36m', False: '\x1b[39m'},
Expand Down Expand Up @@ -636,13 +637,12 @@ def colorize(self, val, color):
def do_cmdenvironment(self, args):
"""Summary report of interactive parameters."""
self.stdout.write("""
Commands are %(casesensitive)scase-sensitive.
Commands may be terminated with: %(terminators)s
Settable parameters: %(settable)s\n""" %
{'casesensitive': (self.case_insensitive and 'not ') or '',
'terminators': str(self.terminators),
'settable': ' '.join(self.settable)
})
Commands are case-sensitive: {}
Commands may be terminated with: {}
Command-line arguments allowed: {}
Output redirection and pipes allowed: {}
Settable parameters: {}\n""".format(not self.case_insensitive, str(self.terminators), self.allow_cli_args,
self.allow_redirection, ' '.join(self.settable)))

def do_help(self, arg):
"""List available commands with "help" or detailed help with "help cmd"."""
Expand Down Expand Up @@ -990,15 +990,17 @@ def onecmd_plus_hooks(self, line):
if statement.parsed.command not in self.excludeFromHistory:
self.history.append(statement.parsed.raw)
try:
self.redirect_output(statement)
if self.allow_redirection:
self.redirect_output(statement)
timestart = datetime.datetime.now()
statement = self.precmd(statement)
stop = self.onecmd(statement)
stop = self.postcmd(stop, statement)
if self.timing:
self.pfeedback('Elapsed: %s' % str(datetime.datetime.now() - timestart))
finally:
self.restore_output(statement)
if self.allow_redirection:
self.restore_output(statement)
except EmptyStatement:
return 0
except ValueError as ex:
Expand Down
25 changes: 21 additions & 4 deletions tests/test_cmd2.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,17 +198,19 @@ def test_base_cmdenvironment(base_app):
out = run_cmd(base_app, 'cmdenvironment')
expected = normalize("""
Commands are not case-sensitive.
Commands are case-sensitive: False
Commands may be terminated with: [';']
Command-line arguments allowed: True
Output redirection and pipes allowed: True
""")
assert out[:2] == expected[:2]
assert out[2].strip().startswith('Settable parameters: ')
assert out[:4] == expected[:4]
assert out[4].strip().startswith('Settable parameters: ')

# Settable parameters can be listed in any order, so need to validate carefully using unordered sets
settable_params = {'continuation_prompt', 'default_file_name', 'prompt', 'abbrev', 'quiet', 'case_insensitive',
'colors', 'echo', 'timing', 'editor', 'feedback_to_output', 'debug', 'autorun_on_edit',
'locals_in_py'}
out_params = set(out[2].split("Settable parameters: ")[1].split())
out_params = set(out[4].split("Settable parameters: ")[1].split())
assert settable_params == out_params


Expand Down Expand Up @@ -330,6 +332,21 @@ def test_output_redirection(base_app):
os.remove(filename)


def test_allow_redirection(base_app):
# Set allow_redirection to False
base_app.allow_redirection = False

filename = 'test_allow_redirect.txt'

# Verify output wasn't redirected
out = run_cmd(base_app, 'help > {}'.format(filename))
expected = normalize(BASE_HELP)
assert out == expected

# Verify that no file got created
assert not os.path.exists(filename)


@pytest.mark.skipif(sys.platform.startswith('linux') and getpass.getuser() == 'travis',
reason="Unit test passes on Ubuntu 16.04 and Debian 8.7, but fails on TravisCI Linux containers")
def test_input_redirection(base_app, request):
Expand Down

0 comments on commit 49059cb

Please sign in to comment.