How to run “ ps cax | grep something ” in Python?

前端 未结 5 1220
小蘑菇
小蘑菇 2020-11-29 03:49

How do I run a command with a pipe | in it?

The subprocess module seems complex...

Is there something like

output,error = `ps ca         


        
5条回答
  •  醉梦人生
    2020-11-29 04:11

    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.

提交回复
热议问题