【问题标题】:run linux grep command from python subprocess从 python 子进程运行 linux grep 命令
【发布时间】:2015-12-19 03:37:46
【问题描述】:

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

/sbin/ifconfig eth1 | grep "inet addr" | awk -F: '{print $2}' | awk '{print $1}'

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

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

非常感谢任何帮助。

【问题讨论】:

标签: python linux grep subprocess


【解决方案1】:

下面是如何在 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 $1}'], stdin=PIPE)
awk1 = Popen([AWK_PATH, '-F:', '{print $2}'], 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()

最好使用re 在 Python 中进行字符串处理。这样做可以获得ifconfig的标准输出。

from subprocess import check_output

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

【讨论】:

  • 您在awk1 上缺少重要的-F : 选项。它导致 Awk 将输入拆分为冒号,而不是空格。当然,整个管道可以只是awk '/inet addr:/ { print substr($2, 6) }'
  • @tripleee 我添加了 -F: 选项。
  • 你应该关闭父进程中的管道,否则你可能会挂起子进程。或start the last command first and pass its stdin pipe to stdout of the preceding command.
  • @PeterSutton:您应该从awk2 获得输出(设置stdout=PIPE,调用communicate())。您仍然应该关闭管道(调用communicate() 而不是wait(),以避免依赖垃圾收集来释放父级中的文件描述符)。
【解决方案2】:

这已经被讨论过很多次了;但这里是一个简单的纯 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:]

【讨论】:

  • @whoopididoo: ip = re.search(br'inet addr:(\S+)', subprocess.check_output(['ifconfig', 'eth1'])).group(1)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-03
  • 1970-01-01
  • 2022-10-19
  • 2017-10-30
  • 2021-12-10
  • 1970-01-01
相关资源
最近更新 更多