简体   繁体   English

如何从 Python 中的命令 output 解析和查找内容

[英]How do I parse and find something from command output in Python

I would like to find only the IP address from the command output of ifconfig :我只想从ifconfig的 output 命令中找到 IP 地址:

import os

ip = os.system("ifconfig eth0")

How do I then find 192.168.1.10 from the output and print that to standard output?然后我如何从 output 中找到192.168.1.10并将其打印到标准 output?

ip=os.system("ifconfig eth0|grep -w 'inet'|awk '{print $2}'")

This solution is with pure shell commands.此解决方案使用纯 shell 命令。 Grep searches for the word inet and prints the line, awk then filters for the second word and this is the IP Grep 搜索单词 inet 并打印该行,awk 然后过滤第二个单词,这是 IP

or或者

import subprocess

import re

ip=subprocess.Popen(['ifconfig', 'eth0'], stdout=subprocess.PIPE).communicate()[0]

oip=re.search(r"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}", str(ip))

print(oip.group())

Here regular expressions are applied to the ifconfig command.这里正则表达式应用于 ifconfig 命令。 The first occurrence of a string is searched for, which has 4 numbers, each number maximum 3 digits long, separated by a dot.搜索第一次出现的字符串,该字符串有 4 个数字,每个数字最长为 3 位,以点分隔。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何解析getmac命令的output? - How do I parse the output of getmac command? 如何从请求 python 中找到以 JSON 中的内容开头的内容 - How do I find something starting with something in JSON from requests python 如何从Python执行复杂的shell find命令? - How do I execute a complex shell find command from Python? Python 子进程 - 运行 shell 命令并执行特定命令 output - Python subprocess - Run shell command and do something on specific command output 我如何找出屏幕上某物的x和位置(python) - How do i find out the x and positions of something on screen (python) 如何在python中解析CLI命令输出(表)? - How to parse a CLI command output (table) in python? 如何防止distutils将-I / usr / include / python2.7添加到gcc命令行? (或将其更改为其他内容) - How do I prevent distutils from adding -I/usr/include/python2.7 to the gcc command line? (or change it to something else) 如何解析 Python 中的 AST 以仅查找变量 - How do I Parse an AST in Python to Find Just the Variables 如何从使用 Python 中的 os.system 库的 cat 命令抑制 output - How do I suppress output from a cat command that uses the os.system library in Python 是否有类似于Python中“ find”命令的内容? - Is there something similar to the “find” command in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM