Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

Let's say I just want to search a dhcpd file for host entries, their IP and MAC, and print them in one line. Here, I want some help with a python script. I can able to find the IP address and hostname but I don't know how to get the variables out of the if statement to put it in one line. Look at the below code and give me some suggestions guys?

#!/usr/bin/python

import sys

import re

#check for arguments

if len(sys.argv) > 1:

    print "usage: no arguments required"

    sys.exit()

else:

    dhcp_file = open("/etc/dhcp/dhcpd.conf","r")

    for line in dhcp_file:

        if re.search(r'\bhost\b',line):

            split = re.split(r'\s+', line)

            print split[1]

        if re.search(r'\bhardware ethernet\b',line):

            ip = re.split(r'\s+',line)

            print ip[2]

    dhcp_file.close()

1 Answer

0 votes
by (26.4k points)

You can achieve this by initializing an empty string before 'if' statement. Then concatenate  split[1] and ip[2] to the empty string and print them. 

Code:

printstr = ""

    if re.search...

        ...

        printstr += "Label for first item " + split[1] + ", "

    if re.search...

        ...

        printstr += "Label for second item " + ip[2]

    print printstr

Wanna become a Python Expert? Come and Join: python training course

For more details, Do check out the tutorial,

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...