我在Python 2.7中具有以下代码,并且收到以下错误。
import os,subprocess,re
f = open("/var/tmp/disks_out", "w")
proc = subprocess.Popen(
["df", "-h"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
out, err = proc.communicate()
for line in out:
f.write(line)
f.close()
f1 = open("/var/tmp/disks_out","r")
disks = []
for line in f1:
m = re.search(r"(c\dt\d.{19})",line)
if m:
disk = m.group[1]
disks.append(disk)
print(disks)
错误:
disk = m.group[1]
TypeError: 'builtin_function_or_method' object is unsubscriptable
有人知道为什么会这样吗?
答案 0 :(得分:1)
您正在做的是-
m.group[1]
但是应该是-
m.group(1)
看here
文档示例-
>>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
>>> m.group(0) # The entire match
'Isaac Newton'
>>> m.group(1) # The first parenthesized subgroup.
'Isaac'
>>> m.group(2) # The second parenthesized subgroup.
'Newton'
>>> m.group(1, 2) # Multiple arguments give us a tuple.
('Isaac', 'Newton')
您正在做的是-
disk=m.group[1]
# Trying to slice a builtin method, in this case, you are trying to slice group()
# and hence
TypeError: 'builtin_function_or_method' object is unsubscriptable
方括号[]
是下标运算符。如果您尝试将下标运算符应用于不支持该运算符的对象,则会出现错误。