从 python 子进程运行 linux grep 命令 [英] run linux grep command from python subprocess

查看:29
本文介绍了从 python 子进程运行 linux grep 命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know there are posts already on how to use subprocess in python to run linux commands but I just cant get the syntax correct for this one. please help. This is the command I need to run...

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

好的,这就是我目前所拥有的,但会出现语法错误...

Ok this is what I have at the moment that gives a syntax error...

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

非常感谢任何帮助.

推荐答案

这之前已经讨论过很多次了;但这里有一个简单的纯 Python 替代品,用于替代低效的后处理.

This has been gone over many, many times before; but here is a simple pure Python replacement for the inefficient postprocessing.

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

这篇关于从 python 子进程运行 linux grep 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆