python - 为什么我不能对此子流程模块方法返回的“字符串”执行正则表达式?
问题描述
我在 Python 中很新,我发现正则表达式有一些问题
在我正在使用的程序中,我有这些代码行:
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))
第一行在 Linux 系统上执行ifconfig命令(使用 subprocess 模块)。然后我打印这个输出,我得到这个输出:
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'
然后我尝试使用正则表达式仅提取包含在此返回的“字符串”中的 MAC 地址(我认为这不是一个合适的字符串)。
问题是在这条线上执行正则表达式:
mac_address_search_result = re.search(r"\w\w:\w\w:\w\w:\w\w:\w\w:\w\w", ifconfig_result)
我得到以下异常:
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
所以在我看来,子进程对象的 check_output() 方法返回的 ifconfig_result 对象不是字符串,而是类似于二进制的东西(究竟是什么)
为什么我会有这种行为?(我正在关注一个以这种方式说明的教程)。
我怎样才能获得一个合适的字符串,以便我可以使用我的正则表达式?
解决方案
“字节文字总是以'b'或'B'为前缀;它们产生字节类型而不是str类型的实例。它们只能包含ASCII字符;数值为128或更大的字节必须用转义表示。”
推荐阅读
- c# - ASP.NET 应用程序调用 TLS 1.0 和 TLS 1.2 Web 服务
- java - JPA Query.getResultsList failing on table with composite key
- html - Bootstrap 4列未按预期对齐
- database - 我的模拟器不使用相同的数据库,如果我在不同的设备上安装我的应用程序也会发生这种情况?
- javascript - [React Native+Firebase]How do you traverse a nested javascript array of objects and print the lowest child. ? (Firebase+React Native)
- python - Self.X Python (OOP)
- python - Click font awesome button python & selenium
- python - 从另一个 python 文件中获取变量。无属性错误
- svg - How to use Viewbox to show server-generated SVG?
- ruby-on-rails - 如何从印象派的轨道上获取时间范围?