How to use `subprocess` command with pipes

后端 未结 9 1444
春和景丽
春和景丽 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 03:07

    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:

    query = "process_name"
    ps_process = Popen(["ps", "-A"], stdout=PIPE)
    grep_process = Popen(["grep", query], stdin=ps_process.stdout, stdout=PIPE)
    ps_process.stdout.close()  # Allow ps_process to receive a SIGPIPE if grep_process exits.
    output = grep_process.communicate()[0]
    

提交回复
热议问题