如何在Python中运行"ps cax | grep something"?

eug*_*ene 26 python command pipe

如何运行带有管道的命令|

子进程模块看起来很复杂......

有没有类似的东西

output,error = `ps cax | grep something`
Run Code Online (Sandbox Code Playgroud)

在shell脚本中?

unu*_*tbu 50

请参阅替换shell管道:

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))
Run Code Online (Sandbox Code Playgroud)

PS.使用shell=True可能很危险.例如,请参阅文档中的警告.


还有sh模块可以使Python中的子进程脚本更加愉快:

import sh
print(sh.grep(sh.ps("cax"), 'something'))
Run Code Online (Sandbox Code Playgroud)

  • `sh.grep(sh.ps('aux', _piped=True), 'something')` - 为我工作 (3认同)
  • 对 sh 模块的重要参考,我强烈推荐它。 (2认同)

Kir*_*ser 17

你已经接受了答案,但是:

你真的需要用grep吗?我写的东西像:

import subprocess
ps = subprocess.Popen(('ps', 'cax'), stdout=subprocess.PIPE)
output = ps.communicate()[0]
for line in output.split('\n'):
    if 'something' in line:
        ...
Run Code Online (Sandbox Code Playgroud)

这样做的好处是不涉及shell=True它的风险,不会分离出一个单独的grep进程,看起来很像你用来处理数据文件类对象的那种Python.


ins*_*tor 10

import subprocess

process = subprocess.Popen("ps cax | grep something",
                             shell=True,
                             stdout=subprocess.PIPE,
                           )
stdout_list = process.communicate()[0].split('\n')
Run Code Online (Sandbox Code Playgroud)

  • @Eugene:您可以使用变量构造字符串,但要注意变量的来源.即确保它不是来自用户可以将"某些东西"变成"某事物; rm -rf /"`.构建使用shell = True运行的表达式可能存在安全风险. (3认同)

Mic*_*ent 7

删除'ps'子进程并慢慢退回!:)

请改用psutil模块.

  • 我想使用psutil,但如果没有显示它将如何完成,这个答案并不是很有帮助. (4认同)
  • `导入psutil;对于 psutil.process_iter() 中的 proc: cmdline = " ".join(proc.cmdline()); 如果 cmdline 中有内容:break` (2认同)