[英]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 它可能听起来有点小说,但我说我从模块psutils调用一个函数,有没有办法说出我想要的值
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? 有没有办法让它只返回B和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(): 根据dm03514的帖子,我建议您使用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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.