Skip to content

Commit eb5246a

Browse files
committed
Fix flake8 errors
1 parent c3e7b16 commit eb5246a

File tree

4 files changed

+135
-100
lines changed

4 files changed

+135
-100
lines changed

gpustat/__main__.py

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,15 @@ def print_gpustat(json=False, debug=False, **args):
1515
try:
1616
gpu_stats = GPUStatCollection.new_query()
1717
except Exception as e:
18-
sys.stderr.write('Error on querying NVIDIA devices. Use --debug flag for details\n')
18+
sys.stderr.write('Error on querying NVIDIA devices.'
19+
' Use --debug flag for details\n')
1920
if debug:
2021
try:
2122
import traceback
2223
traceback.print_exc(file=sys.stderr)
23-
except:
24-
# NVMLError can't be processed by traceback: https://bugs.python.org/issue28603
24+
except Exception as e:
25+
# NVMLError can't be processed by traceback:
26+
# https://bugs.python.org/issue28603
2527
# as a workaround, simply re-throw the exception
2628
raise e
2729
sys.exit(1)
@@ -56,19 +58,27 @@ def main(*argv):
5658
help='Display username of running process')
5759
parser.add_argument('-p', '--show-pid', action='store_true',
5860
help='Display PID of running process')
59-
parser.add_argument('-P', '--show-power', nargs='?', const='draw,limit',
60-
choices=['', 'draw', 'limit', 'draw,limit', 'limit,draw'],
61-
help='Show GPU power usage or draw (and/or limit)')
62-
parser.add_argument('--no-header', dest='show_header', action='store_false', default=True,
63-
help='Suppress header message')
64-
parser.add_argument('--gpuname-width', type=int, default=16,
65-
help='The minimum column width of GPU names, defaults to 16')
6661
parser.add_argument('--json', action='store_true', default=False,
6762
help='Print all the information in JSON format')
68-
parser.add_argument('--debug', action='store_true', default=False,
69-
help='Allow to print additional informations for debugging.')
7063
parser.add_argument('-v', '--version', action='version',
7164
version=('gpustat %s' % __version__))
65+
parser.add_argument(
66+
'-P', '--show-power', nargs='?', const='draw,limit',
67+
choices=['', 'draw', 'limit', 'draw,limit', 'limit,draw'],
68+
help='Show GPU power usage or draw (and/or limit)'
69+
)
70+
parser.add_argument(
71+
'--no-header', dest='show_header', action='store_false', default=True,
72+
help='Suppress header message'
73+
)
74+
parser.add_argument(
75+
'--gpuname-width', type=int, default=16,
76+
help='The minimum column width of GPU names, defaults to 16'
77+
)
78+
parser.add_argument(
79+
'--debug', action='store_true', default=False,
80+
help='Allow to print additional informations for debugging.'
81+
)
7282
args = parser.parse_args(argv[1:])
7383

7484
print_gpustat(**vars(args))

gpustat/core.py

Lines changed: 83 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -18,28 +18,25 @@
1818
import sys
1919
from datetime import datetime
2020

21-
import six
2221
from six.moves import cStringIO as StringIO
2322

2423
import psutil
2524
import pynvml as N
2625
from blessings import Terminal
2726

2827
NOT_SUPPORTED = 'Not Supported'
28+
MB = 1024 * 1024
2929

3030

3131
class GPUStat(object):
3232

3333
def __init__(self, entry):
3434
if not isinstance(entry, dict):
35-
raise TypeError('entry should be a dict, {} given'.format(type(entry)))
35+
raise TypeError(
36+
'entry should be a dict, {} given'.format(type(entry))
37+
)
3638
self.entry = entry
3739

38-
# Handle '[Not Supported] for old GPU cards (#6)
39-
for k in self.entry.keys():
40-
if isinstance(self.entry[k], six.string_types) and NOT_SUPPORTED in self.entry[k]:
41-
self.entry[k] = None
42-
4340
def __repr__(self):
4441
return self.print_to(StringIO()).getvalue()
4542

@@ -96,7 +93,8 @@ def memory_free(self):
9693
@property
9794
def memory_available(self):
9895
"""
99-
Returns the available memory (in MB) as an integer. Alias of memory_free.
96+
Returns the available memory (in MB) as an integer.
97+
Alias of memory_free.
10098
"""
10199
return self.memory_free
102100

@@ -141,8 +139,7 @@ def processes(self):
141139
"""
142140
Get the list of running processes on the GPU.
143141
"""
144-
return list(self.entry['processes'])
145-
142+
return self.entry['processes']
146143

147144
def print_to(self, fp,
148145
with_colors=True, # deprecated arg
@@ -159,38 +156,41 @@ def print_to(self, fp,
159156
def _conditional(cond_fn, true_value, false_value,
160157
error_value=term.bold_black):
161158
try:
162-
if cond_fn(): return true_value
163-
else: return false_value
164-
except:
159+
return cond_fn() and true_value or false_value
160+
except Exception:
165161
return error_value
166162

167163
colors['C0'] = term.normal
168164
colors['C1'] = term.cyan
169165
colors['CName'] = term.blue
170-
colors['CTemp'] = _conditional(lambda: int(self.entry['temperature.gpu']) < 50,
166+
colors['CTemp'] = _conditional(lambda: self.temperature < 50,
171167
term.red, term.bold_red)
172168
colors['CMemU'] = term.bold_yellow
173169
colors['CMemT'] = term.yellow
174170
colors['CMemP'] = term.yellow
175171
colors['CUser'] = term.bold_black # gray
176-
colors['CUtil'] = _conditional(lambda: int(self.entry['utilization.gpu']) < 30,
172+
colors['CUtil'] = _conditional(lambda: self.utilization < 30,
177173
term.green, term.bold_green)
178-
colors['CPowU'] = _conditional(lambda: float(self.entry['power.draw']) / self.entry['enforced.power.limit'] < 0.4,
179-
term.magenta, term.bold_magenta)
174+
colors['CPowU'] = _conditional(
175+
lambda: float(self.power_draw) / self.power_limit < 0.4,
176+
term.magenta, term.bold_magenta
177+
)
180178
colors['CPowL'] = term.magenta
181179

182180
if not with_colors:
183181
for k in list(colors.keys()):
184182
colors[k] = ''
185183

186184
def _repr(v, none_value='??'):
187-
if v is None: return none_value
188-
else: return str(v)
185+
return none_value if v is None else v
189186

190187
# build one-line display information
191-
# we want power use optional, but if deserves being grouped with temperature and utilization
192-
reps = "%(C1)s[{entry[index]}]%(C0)s %(CName)s{entry[name]:{gpuname_width}}%(C0)s |" \
193-
"%(CTemp)s{entry[temperature.gpu]:>3}'C%(C0)s, %(CUtil)s{entry[utilization.gpu]:>3} %%%(C0)s"
188+
# we want power use optional, but if deserves being grouped with
189+
# temperature and utilization
190+
reps = "%(C1)s[{entry[index]}]%(C0)s " \
191+
"%(CName)s{entry[name]:{gpuname_width}}%(C0)s |" \
192+
"%(CTemp)s{entry[temperature.gpu]:>3}'C%(C0)s, " \
193+
"%(CUtil)s{entry[utilization.gpu]:>3} %%%(C0)s"
194194

195195
if show_power:
196196
reps += ", %(CPowU)s{entry[power.draw]:>3}%(C0)s "
@@ -200,31 +200,40 @@ def _repr(v, none_value='??'):
200200
else:
201201
reps += "%(CPowU)sW%(C0)s"
202202

203-
reps += " | %(C1)s%(CMemU)s{entry[memory.used]:>5}%(C0)s / %(CMemT)s{entry[memory.total]:>5}%(C0)s MB"
203+
reps += " | %(C1)s%(CMemU)s{entry[memory.used]:>5}%(C0)s " \
204+
"/ %(CMemT)s{entry[memory.total]:>5}%(C0)s MB"
204205
reps = (reps) % colors
205-
reps = reps.format(entry={k: _repr(v) for (k, v) in self.entry.items()},
206+
reps = reps.format(entry={k: _repr(v) for k, v in self.entry.items()},
206207
gpuname_width=gpuname_width)
207208
reps += " |"
208209

209210
def process_repr(p):
210211
r = ''
211212
if not show_cmd or show_user:
212-
r += "{CUser}{}{C0}".format(_repr(p['username'], '--'), **colors)
213+
r += "{CUser}{}{C0}".format(
214+
_repr(p['username'], '--'), **colors
215+
)
213216
if show_cmd:
214-
if r: r += ':'
215-
r += "{C1}{}{C0}".format(_repr(p.get('command', p['pid']), '--'), **colors)
217+
if r:
218+
r += ':'
219+
r += "{C1}{}{C0}".format(
220+
_repr(p.get('command', p['pid']), '--'), **colors
221+
)
216222

217223
if show_pid:
218224
r += ("/%s" % _repr(p['pid'], '--'))
219-
r += '({CMemP}{}M{C0})'.format(_repr(p['gpu_memory_usage'], '?'), **colors)
225+
r += '({CMemP}{}M{C0})'.format(
226+
_repr(p['gpu_memory_usage'], '?'), **colors
227+
)
220228
return r
221229

222-
if self.entry['processes'] is not None:
223-
for p in self.entry['processes']:
230+
processes = self.entry['processes']
231+
if processes:
232+
for p in processes:
224233
reps += ' ' + process_repr(p)
225234
else:
226235
# None (not available)
227-
reps += ' (Not Supported)'
236+
reps += ' ({})'.format(NOT_SUPPORTED)
228237

229238
fp.write(reps)
230239
return fp
@@ -259,14 +268,16 @@ def get_process_info(nv_process):
259268
process = {}
260269
ps_process = psutil.Process(pid=nv_process.pid)
261270
process['username'] = ps_process.username()
262-
# cmdline returns full path; as in `ps -o comm`, get short cmdnames.
271+
# cmdline returns full path;
272+
# as in `ps -o comm`, get short cmdnames.
263273
_cmdline = ps_process.cmdline()
264-
if not _cmdline: # sometimes, zombie or unknown (e.g. [kworker/8:2H])
274+
if not _cmdline:
275+
# sometimes, zombie or unknown (e.g. [kworker/8:2H])
265276
process['command'] = '?'
266277
else:
267278
process['command'] = os.path.basename(_cmdline[0])
268279
# Bytes to MBytes
269-
process['gpu_memory_usage'] = int(nv_process.usedGpuMemory / 1024 / 1024)
280+
process['gpu_memory_usage'] = nv_process.usedGpuMemory // MB
270281
process['pid'] = nv_process.pid
271282
return process
272283

@@ -279,12 +290,14 @@ def _decode(b):
279290
uuid = _decode(N.nvmlDeviceGetUUID(handle))
280291

281292
try:
282-
temperature = N.nvmlDeviceGetTemperature(handle, N.NVML_TEMPERATURE_GPU)
293+
temperature = N.nvmlDeviceGetTemperature(
294+
handle, N.NVML_TEMPERATURE_GPU
295+
)
283296
except N.NVMLError:
284297
temperature = None # Not supported
285298

286299
try:
287-
memory = N.nvmlDeviceGetMemoryInfo(handle) # in Bytes
300+
memory = N.nvmlDeviceGetMemoryInfo(handle) # in Bytes
288301
except N.NVMLError:
289302
memory = None # Not supported
290303

@@ -295,39 +308,39 @@ def _decode(b):
295308

296309
try:
297310
power = N.nvmlDeviceGetPowerUsage(handle)
298-
except:
311+
except N.NVMLError:
299312
power = None
300313

301314
try:
302315
power_limit = N.nvmlDeviceGetEnforcedPowerLimit(handle)
303-
except:
316+
except N.NVMLError:
304317
power_limit = None
305318

306319
processes = []
307320
try:
308-
nv_comp_processes = N.nvmlDeviceGetComputeRunningProcesses(handle)
321+
nv_comp_processes = \
322+
N.nvmlDeviceGetComputeRunningProcesses(handle)
309323
except N.NVMLError:
310324
nv_comp_processes = None # Not supported
311325
try:
312-
nv_graphics_processes = N.nvmlDeviceGetGraphicsRunningProcesses(handle)
326+
nv_graphics_processes = \
327+
N.nvmlDeviceGetGraphicsRunningProcesses(handle)
313328
except N.NVMLError:
314329
nv_graphics_processes = None # Not supported
315330

316-
if nv_comp_processes is None and nv_graphics_processes is None:
317-
processes = None # Not supported (in both cases)
318-
else:
319-
nv_comp_processes = nv_comp_processes or []
320-
nv_graphics_processes = nv_graphics_processes or []
321-
for nv_process in (nv_comp_processes + nv_graphics_processes):
322-
# TODO: could be more information such as system memory usage,
323-
# CPU percentage, create time etc.
324-
try:
325-
process = get_process_info(nv_process)
326-
processes.append(process)
327-
except psutil.NoSuchProcess:
328-
# TODO: add some reminder for NVML broken context
329-
# e.g. nvidia-smi reset or reboot the system
330-
pass
331+
processes = []
332+
nv_comp_processes = nv_comp_processes or []
333+
nv_graphics_processes = nv_graphics_processes or []
334+
for nv_process in nv_comp_processes + nv_graphics_processes:
335+
# TODO: could be more information such as system memory usage,
336+
# CPU percentage, create time etc.
337+
try:
338+
process = get_process_info(nv_process)
339+
processes.append(process)
340+
except psutil.NoSuchProcess:
341+
# TODO: add some reminder for NVML broken context
342+
# e.g. nvidia-smi reset or reboot the system
343+
pass
331344

332345
index = N.nvmlDeviceGetIndex(handle)
333346
gpu_info = {
@@ -336,11 +349,12 @@ def _decode(b):
336349
'name': name,
337350
'temperature.gpu': temperature,
338351
'utilization.gpu': utilization.gpu if utilization else None,
339-
'power.draw': int(power / 1000) if power is not None else None,
340-
'enforced.power.limit': int(power_limit / 1000) if power_limit is not None else None,
352+
'power.draw': power // 1000 if power is not None else None,
353+
'enforced.power.limit': power_limit // 1000
354+
if power_limit is not None else None,
341355
# Convert bytes into MBytes
342-
'memory.used': int(memory.used / 1024 / 1024) if memory else None,
343-
'memory.total': int(memory.total / 1024 / 1024) if memory else None,
356+
'memory.used': memory.used // MB if memory else None,
357+
'memory.total': memory.total // MB if memory else None,
344358
'processes': processes,
345359
}
346360
return gpu_info
@@ -382,7 +396,8 @@ def print_formatted(self, fp=sys.stdout, force_color=False, no_color=False,
382396
):
383397
# ANSI color configuration
384398
if force_color and no_color:
385-
raise ValueError("--color and --no_color can't be used at the same time")
399+
raise ValueError("--color and --no_color can't"
400+
" be used at the same time")
386401

387402
if force_color:
388403
t_color = Terminal(kind='xterm-color', force_styling=True)
@@ -395,17 +410,19 @@ def print_formatted(self, fp=sys.stdout, force_color=False, no_color=False,
395410
if show_header:
396411
time_format = locale.nl_langinfo(locale.D_T_FMT)
397412

398-
header_msg = '{t.bold_white}{hostname}{t.normal} {timestr}'.format(**{
399-
'hostname': self.hostname,
400-
'timestr': self.query_time.strftime(time_format),
401-
't': t_color,
402-
})
413+
header_template = '{t.bold_white}{hostname}{t.normal} {timestr}'
414+
header_msg = header_template.format(
415+
hostname=self.hostname,
416+
timestr=self.query_time.strftime(time_format),
417+
t=t_color,
418+
)
403419

404420
fp.write(header_msg)
405421
fp.write('\n')
406422

407423
# body
408-
gpuname_width = max([gpuname_width] + [len(g.entry['name']) for g in self])
424+
entry_name_width = [len(g.entry['name']) for g in self]
425+
gpuname_width = max([gpuname_width] + entry_name_width)
409426
for g in self:
410427
g.print_to(fp,
411428
show_cmd=show_cmd,

0 commit comments

Comments
 (0)