How to execute a command with pipe's in call function module subprocess in python?

There is such a command
screen-ls | tail-n +2 | head -n -2 | awk '{print $1}'| xargs -I{} screen-S {} -X quit

I need it to run in python3.4 , how to do it correctly?
September 19th 19 at 00:20
4 answers
September 19th 19 at 00:22
You need to specify the parameter shell=True
subprocess.call('ls-la | grep i', shell=True)

If you want to process the output / error, it is possible so:
>>> p = subprocess.Popen('ls-la|grep i', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> p
<subprocess.popen object at 0x2173790>
>>> p.stdout
<_io.FileIO name=3 mode='rb'>
>>> p.stdout.read()
>>> p.stderr.read()</subprocess.popen>
September 19th 19 at 00:24
In an example from the off. documentation:

output=`dmesg | grep hda`
# becomes
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]
the script show - Troy.Hermiston commented on September 19th 19 at 00:27
sorry, deleted my comment. with this error I figured out that I'm not as written. below, I have given code that - Javier.Daugherty62 commented on September 19th 19 at 00:30
September 19th 19 at 00:26
screen-ls | tail-n +2 | head -n -2 | awk '{print $1}'| xargs -I{} screen-S {} -X quit


You can try to use:
sh (previously pbs) is a full-fledged subprocess interface for Python that allows you to call any program as if it were a function
amoffat.github.io/sh/#piping

or
Plumbum is a small yet feature-rich library for shell script-like programs in Python
https://plumbum.readthedocs.org/en/latest/#cheat-sheet
September 19th 19 at 00:28
Did
p1 = Popen(['screen', '-la'], stdout=PIPE)
 p2 = Popen(['tail', '-n', '+2'], stdin=p1.stdout, stdout=PIPE)
 p3 = Popen(['head', '-n', '-2'], stdin=p2.stdout, stdout=PIPE)
 p4 = Popen(['awk', '"{print $1}"'], stdin=p3.stdout, stdout=PIPE)
 p5 = Popen(['xargs', '-I{}', 'screen', '-S', '{}', '-X', 'quit'], stdin=p4.stdout, stdout=PIPE)
p1.stdout.close()
p2.stdout.close()
p3.stdout.close()
p4.stdout.close()
 output = p4.communicate[0];
 print(output)

right?
like the truth, only p1, p2 ... - not very good variable names - Troy.Hermiston commented on September 19th 19 at 00:31
: test version:) output = p4.communicate[0]; corrected for output = p5.communicate[0]; , but get TypeError: 'method' object is not subscriptable on the line. Python3.4. What's wrong? - Javier.Daugherty62 commented on September 19th 19 at 00:34
:
p4.communicate()[0]
and the semicolon is not needed - Troy.Hermiston commented on September 19th 19 at 00:37

Find more questions by tags Python