简体   繁体   中英

When calling a function from a module can you say what is returned? (Python)

It may sound a bit noobish but say i call a function from the module psutils, is there a way to say which value i want back

for example:

    psutil.swap_memory()

returns

    swap(total=A, used=B, free=C, percent=D, sin=0, sout=0)

is there a way to make it only return B and C?

There are a few ways, the most obvious being:

info = psutil.swap_memory()
used, free = info.used, info.free

The returned object is actually a tuple-like object, so you could also slice it and then unpack it:

used, free = psutil.swap_memory()[1:3]

There's also the more convoluted approach, which has the advantage of ignoring order:

from operator import attgetter

used, free = attrgetter('used', 'free')(psutil.swap_memory())

Based on dm03514's posting, I suggest you use a customized wrapper for swap_memory():

def my_swap_memory():
    _, used, free, _, _, _ = psutil.swap_memory()
    return swap(B=used, C=free)

and then call it like

returndata = my_swap_memory()

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