AndreaNobili
AndreaNobili

Reputation: 42967

Why I can't perform a regex on this "string" returned by this subprocess module method?

I am pretty new in Python and I am finding some problem with regex

Into a program on which I am working I have these lines of code:

ifconfig_result = subprocess.check_output(["ifconfig", options.interface])
print(ifconfig_result)

mac_address_search_result = re.search(r"\w\w:\w\w:\w\w:\w\w:\w\w:\w\w", ifconfig_result)
print(mac_address_search_result.group(0))

The first line perform an ifconfig command on a Linux system (using the subprocess module). Then I print this output, I am obtaining this output:

b'eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500\n        inet 192.168.223.128  netmask 255.255.255.0  broadcast 192.168.223.255\n        inet6 fe80::20c:29ff:feb9:fdf6  prefixlen 64  scopeid 0x20<link>\n        ether 00:0c:29:b9:fd:f6  txqueuelen 1000  (Ethernet)\n        RX packets 69731  bytes 94090876 (89.7 MiB)\n        RX errors 0  dropped 0  overruns 0  frame 0\n        TX packets 31405  bytes 3383293 (3.2 MiB)\n        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0\n\n'

Then I am trying to use a regex to extract only the MAC address containing in this returned "string" (I think that this is not a propper string).

The problem is that on this line performing the regex:

mac_address_search_result = re.search(r"\w\w:\w\w:\w\w:\w\w:\w\w:\w\w", ifconfig_result)

I obtain the following exception:

Traceback (most recent call last):
  File "mac_changer.py", line 46, in <module>
    mac_address_search_result = re.search(r"\w\w:\w\w:\w\w:\w\w:\w\w:\w\w", ifconfig_result)
  File "/usr/lib/python3.7/re.py", line 183, in search
    return _compile(pattern, flags).search(string)
TypeError: cannot use a string pattern on a bytes-like object

So it seems to me that the ifconfig_result objet returned by the check_output() method of the subprocess object is not a string but something like binary (what exactly is)

Why have I this behavior? (I am following a tutorial where it is illustrated in this way).

How can I obtain a propper string so I can use my regex?

Upvotes: 0

Views: 105

Answers (2)

Your problem is that what you have is not a str but a bytes.

Either you convert it to a str

mac_address_search_result = re.search(r"\w\w:\w\w:\w\w:\w\w:\w\w:\w\w", ifconfig_result.decode("utf8"))

Or you use a bytes matcher

mac_address_search_result = re.search(rb"\w\w:\w\w:\w\w:\w\w:\w\w:\w\w", ifconfig_result)

Upvotes: 1

JDunken
JDunken

Reputation: 463

"Bytes literals are always prefixed with 'b' or 'B'; they produce an instance of the bytes type instead of the str type. They may only contain ASCII characters; bytes with a numeric value of 128 or greater must be expressed with escapes."

What does the 'b' character do in front of a string literal?

Upvotes: 1

Related Questions