Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

running a command line containing Pipes and displaying result to STDOUT

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`; 
like image 387
spudATX Avatar asked Sep 08 '11 18:09

spudATX


People also ask

How do you pipe a command output?

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.

How do you pipe output to a file?

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.

Which character is used to pipe output from one command to another?

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!


1 Answers

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') 
like image 170
unutbu Avatar answered Sep 28 '22 19:09

unutbu