summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rwxr-xr-xcmd2.py21
-rw-r--r--tests/test_cmd2.py25
2 files changed, 28 insertions, 18 deletions
diff --git a/cmd2.py b/cmd2.py
index 10b12516..ca431279 100755
--- a/cmd2.py
+++ b/cmd2.py
@@ -900,17 +900,16 @@ class Cmd(cmd.Cmd):
self.kept_state = None
if statement.parsed.pipeTo:
- # cat the tempfile and pipe the output to the specified shell command
- cat_command = 'cat'
- p1 = subprocess.Popen([cat_command, self._temp_filename], stdout=subprocess.PIPE)
- p2 = subprocess.Popen(shlex.split(statement.parsed.pipeTo), stdin=p1.stdout, stdout=subprocess.PIPE)
- p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
- output, err = p2.communicate()
-
- if six.PY3:
- self.stdout.write(output.decode())
- else:
- self.stdout.write(output)
+ # Pipe the contents of tempfile to the specified shell command
+ with open(self._temp_filename) as fd:
+ pipe_proc = subprocess.Popen(shlex.split(statement.parsed.pipeTo), stdin=fd,
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ output, err = pipe_proc.communicate()
+
+ if six.PY3:
+ self.stdout.write(output.decode())
+ else:
+ self.stdout.write(output)
os.remove(self._temp_filename)
self._temp_filename = None
diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py
index adf47d31..d294cd90 100644
--- a/tests/test_cmd2.py
+++ b/tests/test_cmd2.py
@@ -402,15 +402,26 @@ def test_input_redirection(base_app, request):
def test_pipe_to_shell(base_app):
- # Get help on help and pipe it's output to the input of the word count shell command
- out = run_cmd(base_app, 'help help | wc')
-
if sys.platform == "win32":
- expected = normalize("1 11 71")
+ # Windows
+ # Get help menu and pipe it's output to the sort shell command
+ out = run_cmd(base_app, 'help | sort')
+ expected = ['', '', '_relative_load edit history pause pyscript run set shortcuts',
+ '========================================',
+ 'cmdenvironment help load py quit save shell show',
+ 'Documented commands (type help <topic>):']
+ assert out == expected
else:
- expected = normalize("1 11 70")
-
- assert out[0].strip() == expected[0].strip()
+ # Mac and Linux
+ # Get help on help and pipe it's output to the input of the word count shell command
+ out = run_cmd(base_app, 'help help | wc')
+
+ # Mac and Linux wc behave the same when piped from shell, but differently when piped stdin from file directly
+ if sys.platform == 'darwin':
+ expected = normalize("1 11 70")
+ else:
+ expected = normalize("1 11 70")
+ assert out[0].strip() == expected[0].strip()
def test_send_to_paste_buffer(base_app):