如何让此命令与子进程一起使用?

时间:2017-09-15 16:24:49

标签: python subprocess

我无法使用此命令来处理子进程:

tail -f -n 1 /mnt/syslog/**/*.log | grep -Ev ''mnt|^$'

这是我的代码:

import subprocess

tail = subprocess.Popen('tail -f -n 1 /mnt/syslog/**/*.log | grep -Ev ''mnt|^$''', shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)

while True:
    line = tail.stdout.readline()
    line = line.strip('\n')
    print line

没有任何内容可以打印到屏幕上。但是,当我在shell中键入tail命令时 - 它完全正常,我收到输出:

root@jumpbox:~# tail -f -n 1 /mnt/syslog/**/*.log | grep -Ev 'mnt|^$'
Sep 14 16:06:35 x.x.x.x : %LINK-5-CHANGED: Interface GigabitEthernet1/0/19, changed state to administratively down
Sep 14 16:06:35 x.x.x.x : %LINK-5-CHANGED: Interface GigabitEthernet1/0/19, changed state to administratively down

我有一种感觉它或者不喜欢引号或管道?

1 个答案:

答案 0 :(得分:2)

此字符串文字:

'tail -f -n 1 /mnt/syslog/**/*.log | grep -Ev ''mnt|^$'''

实际上是三个单独的单引号字符串一起运行:

'tail -f -n 1 /mnt/syslog/**/*.log | grep -Ev '
'mnt|^$'
''

所以你正在执行的实际命令是:

tail -f -n 1 /mnt/syslog/**/*.log | grep -Ev mnt|^$

这根本不是您想要的 - 请注意您正在将grep的输出传递给不存在的^$程序!基本上,这纯粹是巧合,结果证明它在语法上是有效的。你需要为整个字符串使用不同形式的引用(在这种情况下双引号可以工作),或者使用反斜杠转义内部引号。