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

前端 未结 5 1207
小蘑菇
小蘑菇 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 03:55

    Drop that 'ps' subprocess and back away slowly! :)

    Use the psutil module instead.

    0 讨论(0)
  • 2020-11-29 04:00
    import subprocess
    
    process = subprocess.Popen("ps cax | grep something",
                                 shell=True,
                                 stdout=subprocess.PIPE,
                               )
    stdout_list = process.communicate()[0].split('\n')
    
    0 讨论(0)
  • 2020-11-29 04:07
    import os
    
    os.system('ps -cax|grep something')
    

    If you wanna replace grep argument with some variable:

    os.system('ps -cax|grep '+your_var)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-29 04:17

    See Replacing shell pipeline:

    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'))
    
    0 讨论(0)
提交回复
热议问题