[英]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.