Skip to content

Commit 9054a21

Browse files
committed
shell command now uses cmd.Cmd.stdout for output
The main advantages of this are that shell command output can now be - piped to another shell command - redirected to a file In the future, I may take it a step further where the output is piped, but using a pipe versus a real terminal changes the behavior of many shell commands, for example by getting rid of ANSI color and various other pretty formatting.
1 parent cc7a330 commit 9054a21

2 files changed

Lines changed: 4 additions & 12 deletions

File tree

cmd2.py

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1138,21 +1138,15 @@ def do_pause(self, text):
11381138
Usage: pause [text]"""
11391139
sm.input(text + '\n')
11401140

1141-
# noinspection PyMethodMayBeStatic
11421141
def do_shell(self, command):
11431142
"""Execute a command as if at the OS prompt.
11441143
11451144
Usage: shell <command> [arguments]"""
11461145
try:
1147-
out = subprocess.check_output(shlex.split(command))
1148-
except subprocess.CalledProcessError as e:
1149-
self.perror(e, traceback_war=False)
1146+
proc = subprocess.Popen(command, stdout=self.stdout, stderr=sys.stderr, shell=True)
1147+
proc.communicate()
11501148
except FileNotFoundError as e:
1151-
self.perror(e, traceback_war=False)
1152-
else:
1153-
if six.PY3:
1154-
out = out.decode()
1155-
self.stdout.write(out + '\n')
1149+
self.perror(e.strerror, traceback_war=False)
11561150

11571151
def path_complete(self, text, line, begidx, endidx, dir_exe_only=False, dir_only=False):
11581152
"""Method called to complete an input line by local file system path completion.

tests/test_cmd2.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -103,12 +103,10 @@ def test_base_set_not_supported(base_app, capsys):
103103

104104
def test_base_shell(base_app, monkeypatch):
105105
m = mock.Mock()
106-
monkeypatch.setattr("os.system", m)
106+
monkeypatch.setattr("subprocess.Popen", m)
107107
out = run_cmd(base_app, 'shell echo a')
108108
assert out == []
109109
assert m.called
110-
m.assert_called_with('echo a')
111-
112110

113111
def test_base_py(base_app, capsys):
114112
run_cmd(base_app, 'py qqq=3')

0 commit comments

Comments
 (0)