@@ -46,25 +46,47 @@ def get_option_parser():
46
46
return OptionParser (__doc__ )
47
47
48
48
49
+ def _call_psutil_interface (interface , * args ):
50
+ """Call a psutil interface with the provided arguments.
51
+
52
+ Args:
53
+ interface:
54
+ The psutil method we want to call, e.g. "cpu_percent".
55
+
56
+ In the case of objects, this may include attributes, e.g.
57
+ "Process.cmdline".
58
+ args:
59
+ The arguments to provide to the psutil method.
60
+
61
+ Returns:
62
+ The result of the psutil method call.
63
+
64
+ """
65
+ result = psutil
66
+ is_first = True
67
+ for fcn in interface .split ('.' ):
68
+ try :
69
+ method = getattr (result , fcn )
70
+ except AttributeError as exc :
71
+ # error obtaining interfaces from psutil e.g:
72
+ # * requesting a method which does not exist
73
+ print (exc , file = sys .stderr )
74
+ sys .exit (2 )
75
+
76
+ if is_first :
77
+ is_first = False
78
+ else :
79
+ args = ()
80
+
81
+ result = method (* args )
82
+ return result
83
+
84
+
49
85
def _psutil (metrics_json ):
50
86
metrics = parse_dirty_json (metrics_json )
51
87
52
88
try :
53
- methods = [
54
- getattr (psutil , key [0 ])
55
- for key in metrics
56
- ]
57
- except AttributeError as exc :
58
- # error obtaining interfaces from psutil e.g:
59
- # * requesting a method which does not exist
60
- print (exc , file = sys .stderr )
61
- sys .exit (2 )
62
-
63
- try :
64
- ret = [
65
- method (* key [1 :])
66
- for key , method in zip (metrics , methods )
67
- ]
89
+ ret = [_call_psutil_interface (* key ) for key in metrics ]
68
90
except Exception as exc :
69
91
# error extracting metrics from psutil e.g:
70
92
# * requesting information on a resource which does not exist
0 commit comments