How to use `subprocess` command with pipes

后端 未结 9 1441
春和景丽
春和景丽 2020-11-22 02:32

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

相关标签:
9条回答
  • 2020-11-22 02:47

    Using subprocess.run

    import subprocess
    
    ps = subprocess.run(['ps', '-A'], check=True, capture_output=True)
    processNames = subprocess.run(['grep', 'process_name'], input=ps.stdout)
    print(processNames.stdout)
    
    0 讨论(0)
  • 2020-11-22 02:50

    You can try the pipe functionality in sh.py:

    import sh
    print sh.grep(sh.ps("-ax"), "process_name")
    
    0 讨论(0)
  • 2020-11-22 02:51

    To use a pipe with the subprocess module, you have to pass shell=True.

    However, this isn't really advisable for various reasons, not least of which is security. Instead, create the ps and grep processes separately, and pipe the output from one into the other, like so:

    ps = subprocess.Popen(('ps', '-A'), stdout=subprocess.PIPE)
    output = subprocess.check_output(('grep', 'process_name'), stdin=ps.stdout)
    ps.wait()
    

    In your particular case, however, the simple solution is to call subprocess.check_output(('ps', '-A')) and then str.find on the output.

    0 讨论(0)
  • 2020-11-22 02:52

    Or you can always use the communicate method on the subprocess objects.

    cmd = "ps -A|grep 'process_name'"
    ps = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
    output = ps.communicate()[0]
    print(output)
    

    The communicate method returns a tuple of the standard output and the standard error.

    0 讨论(0)
  • 2020-11-22 03:01

    Also, try to use 'pgrep' command instead of 'ps -A | grep 'process_name'

    0 讨论(0)
  • 2020-11-22 03:02

    After Python 3.5 you can also use:

        import subprocess
    
        f = open('test.txt', 'w')
        process = subprocess.run(['ls', '-la'], stdout=subprocess.PIPE, universal_newlines=True)
        f.write(process.stdout)
        f.close()
    

    The execution of the command is blocking and the output will be in process.stdout.

    0 讨论(0)
提交回复
热议问题