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

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

问题描述

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

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

好的,这是我现在有的语法错误...
$ b $ pre $ $ $ $ c $进口子进程
self.ip = subprocess.Popen([/ sbin / ifconfig eth1 | grep inet addr| awk -F:'{print $ 2}'| awk'{print $ 1}'])

任何帮助我们都非常感谢。

解决方案

但是这里是一个用于低效后处理的简单纯Python替换。

  from子进程import Popen,PIPE 
eth1 =子进程.Popen(['sbin / ifconfig','eth1'],stdout = PIPE)
out,err = eth1.communicate()
out.split('\ n') :
line = line.lstrip()
如果line.startswith('inet addr:'):
ip = line.split()[1] [5:]


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}'])

Any help greatly appreciated.

解决方案

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('\n'):
    line = line.lstrip()
    if line.startswith('inet addr:'):
        ip = line.split()[1][5:]

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

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