Python如何在cli中为pgrep转义选项参数

时间:2016-05-07 15:56:06

标签: python shell scripting

我正在尝试使用rsync命令准备一个命令以查明我的ps进程是否正在运行,当我运行脚本时,pgrep将错误视为无效选项,我想知道如何在下面的变量self.getSrcCount中转义命令。

for n in range(0, len(self.chkMntPoints)):
    self.chkMntPoints[n]  = self.chkMntPoints[n].replace('\/','/')
    self.getSrcCount      = 'ps aux | pgrep'+' '+'rsync'+' '+'-avz'+' '+'--progress'+' '+self.chkMntPoints[n]
    print self.getSrcCount
    self.srcWord          = subprocess.Popen(self.getSrcCount, shell=True, stdout=subprocess.PIPE,)
    self.srcWc            = self.srcWord.communicate()[0].strip()
    print self.srcWc
    print len(self.srcWc)
    return len(self.srcWc)


Below is my output after the code execution:

pgrep: invalid option -- a
Usage: pgrep [-flvx] [-d DELIM] [-n|-o] [-P PPIDLIST] [-g PGRPLIST] [-s SIDLIST]
        [-u EUIDLIST] [-U UIDLIST] [-G GIDLIST] [-t TERMLIST] [PATTERN]

0
pgrep: invalid option -- a
Usage: pgrep [-flvx] [-d DELIM] [-n|-o] [-P PPIDLIST] [-g PGRPLIST] [-s SIDLIST]
        [-u EUIDLIST] [-U UIDLIST] [-G GIDLIST] [-t TERMLIST] [PATTERN]

0

1 个答案:

答案 0 :(得分:0)

这不是您问题的直接答案,而是简化问题的替代解决方案。您可以使用psutil库来检索有关正在运行的进程的信息:https://pypi.python.org/pypi/psutil。迭代所有正在运行的进程并检查名称和启动参数很容易:

import psutil
for proc in psutil.process_iter():
    print proc.name(), proc.cmdline()

文档:https://pythonhosted.org/psutil/