I want to use subprocess.check_output()
with ps -A | grep 'process_name'
. I tried various solutions but so far nothing worked. Can someone guide me how to do it?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
To use a pipe with the
subprocess
module, you have to passshell=True
.However, this isn't really advisable for various reasons, not least of which is security. Instead, create the
ps
andgrep
processes separately, and pipe the output from one into the other, like so:In your particular case, however, the simple solution is to call
subprocess.check_output(('ps', '-A'))
and thenstr.find
on the output.or you can use always the communicate method on subprocess objects.
communicate method returns in a tuple the standard output and the standard error.
See the documentation on setting up a pipeline using subprocess: http://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline
I haven't tested the following code example but it should be roughly what you want:
JKALAVIS solution is good, however I would add an improvement to use shlex instead of SHELL=TRUE. below im grepping out Query times
Cheers,
Also, try to use
'pgrep'
command instead of'ps -A | grep 'process_name'
You can try the pipe functionality in sh.py: