How would one call a shell command from Python which contains a pipe and capture the output?
Suppose the command was something like:
cat file.log | tail -1
The Perl equivalent of what I am trying to do would be something like:
my $string = `cat file.log | tail -1`;
Use a subprocess.PIPE, as explained in the subprocess docs section "Replacing shell pipeline":
Or, using the
sh
module, piping becomes composition of functions:Note that this does not capture stderr. And if you want to capture stderr as well, you'll need to use
task.communicate()
; callingtask.stdout.read()
and thentask.stderr.read()
can deadlock if the buffer for stderr fills. If you want them combined, you should be able to use2>&1
as part of the shell command.But given your exact case,
avoids the need for the pipe at all.
Simple function for run shell command with many pipes
Using
Function
This:
Or this should work:
This is a fork from @chown with some improvements:
import subprocess
, makes easier when setting parametersstderr
orstdin
when callingPopen
shell=True
is necessary, in order to call an interpreter for the command lineAnother way similar to Popen would be: