简体   繁体   中英

python 2.7 getting below error while running the script

I have the following code in Python 2.7 and am receiving the following error.

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)

Error:

disk = m.group[1]
TypeError: 'builtin_function_or_method' object is unsubscriptable

Does anyone know why this is happening?

What you are doing is -

m.group[1]

But rather it should be -

m.group(1)

Look here

Example from docs -

>>> 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')

What you are doing instead is-

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

Square brackets [] are the subscript operator. If you try to apply the subscript operator to an object that does not support it, you get the error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM