运行 linux 来自 python 子进程的 grep 命令

run linux grep command from python subprocess

我知道已经有关于如何在 python 到 运行 linux 命令中使用子进程的帖子,但我无法获得正确的语法。请帮忙。这是我需要 运行...

的命令
/sbin/ifconfig eth1 | grep "inet addr" | awk -F: '{print }' | awk '{print }'

好的,这就是我目前遇到的语法错误...

import subprocess
self.ip = subprocess.Popen([/sbin/ifconfig eth1 | grep "inet addr" | awk -F: '{print }' | awk '{print }'])

非常感谢任何帮助。

以下是在 Python 中构建管道的方法(而不是恢复到更难以保护的 Shell=True)。

from subprocess import PIPE, Popen

# Do `which` to get correct paths
GREP_PATH = '/usr/bin/grep'
IFCONFIG_PATH = '/usr/bin/ifconfig'
AWK_PATH = '/usr/bin/awk'

awk2 = Popen([AWK_PATH, '{print }'], stdin=PIPE)
awk1 = Popen([AWK_PATH, '-F:', '{print }'], stdin=PIPE, stdout=awk2.stdin)
grep = Popen([GREP_PATH, 'inet addr'], stdin=PIPE, stdout=awk1.stdin)
ifconfig = Popen([IFCONFIG_PATH, 'eth1'], stdout=grep.stdin)

procs = [ifconfig, grep, awk1, awk2]

for proc in procs:
    print(proc)
    proc.wait()

Python中的字符串处理最好使用re。这样做以获得 ifconfig.

的标准输出
from subprocess import check_output

stdout = check_output(['/usr/bin/ifconfig', 'eth1'])
print(stdout)

这已经讲过很多很多次了;但这里有一个简单的纯 Python 替代低效的后处理。

from subprocess import Popen, PIPE
eth1 = subprocess.Popen(['/sbin/ifconfig', 'eth1'], stdout=PIPE)
out, err = eth1.communicate()
for line in out.split('\n'):
    line = line.lstrip()
    if line.startswith('inet addr:'):
        ip = line.split()[1][5:]