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`;
The > symbol is used to redirect output by taking the output from the command on the left and passing as input to the file on the right.
To redirect the output of a command to a file, type the command, specify the > or the >> operator, and then provide the path to a file you want to the output redirected to. For example, the ls command lists the files and folders in the current directory.
The pipe character | is used to connect the output from one command to the input of another. > is used to redirect standard output to a file. Try it in the shell-lesson-data/exercise-data/proteins directory!
Use a subprocess.PIPE, as explained in the subprocess docs section "Replacing shell pipeline":
import subprocess p1 = subprocess.Popen(["cat", "file.log"], stdout=subprocess.PIPE) p2 = subprocess.Popen(["tail", "-1"], stdin=p1.stdout, stdout=subprocess.PIPE) p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. output,err = p2.communicate()
Or, using the sh
module, piping becomes composition of functions:
import sh output = sh.tail(sh.cat('file.log'), '-1')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With