How do I run a command with a pipe |
in it?
The subprocess module seems complex...
Is there something like
output,error = `ps cax | grep something`
as in shell script?
import subprocess
proc1 = subprocess.Popen(['ps', 'cax'], stdout=subprocess.PIPE)
proc2 = subprocess.Popen(['grep', 'python'], stdin=proc1.stdout,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
proc1.stdout.close() # Allow proc1 to receive a SIGPIPE if proc2 exits.
out, err = proc2.communicate()
print('out: {0}'.format(out))
print('err: {0}'.format(err))
PS. Using shell=True
can be dangerous. See for example the warning in the docs.
There is also the sh module which can make subprocess scripting in Python a lot more pleasant:
import sh
print(sh.grep(sh.ps("cax"), 'something'))
proc1.stdout.close()
should be called?
Dec 27, 2017 at 18:45
find / -print
in proc1
without calling proc1.stdout.close()
and spawn a short-running command like head
in proc2
, then you would see find / -print
is still running long after the call to head
has ended. Including proc1.stdout.close()
allows find
to end soon after head
finishes.
You've already accepted an answer, but:
Do you really need to use grep? I'd write something like:
import subprocess
ps = subprocess.Popen(('ps', 'cax'), stdout=subprocess.PIPE)
output = ps.communicate()[0]
for line in output.split('\n'):
if 'something' in line:
...
This has the advantages of not involving shell=True
and its riskiness, doesn't fork off a separate grep process, and looks an awful lot like the kind of Python you'd write to process data file-like objects.
output
was a [byte] and had to use it like str(output).split("\\n")
Nov 4, 2020 at 9:12
import subprocess
process = subprocess.Popen("ps cax | grep something",
shell=True,
stdout=subprocess.PIPE,
)
stdout_list = process.communicate()[0].split('\n')
'grep %s
% variable`.
"something; rm -rf /"
. Building expressions to run with shell=True is a possible security risk.
Drop that 'ps' subprocess and back away slowly! :)
Use the psutil module instead.
import psutil; for proc in psutil.process_iter(): cmdline = " ".join(proc.cmdline()); if something in cmdline: break
Sep 10, 2018 at 20:44
import os
os.system('ps -cax|grep something')
If you wanna replace grep argument with some variable:
os.system('ps -cax|grep '+your_var)
os.system
only returns the int exit code of the subprocess. If you're running it at an interactive prompt and seeing the output of ps, it's because ps is writing to stout. Python isn't actually capturing that output. Try it yourself: run a = os.system('ls')
. You'll still see the output of ls, and a
will be 0 (assuming ls didn't fail for some reason).
Jul 22, 2011 at 16:05
your_var
is set by someone else, this code lets them run any command they want. For example your_var = "a; echo you got hacked"
Dec 27, 2019 at 4:16
subprocess
. It's much easier to do this with the shell. Indeed, this is the one thing the shell does best.