diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 00000000..26c94ab9 --- /dev/null +++ b/.pylintrc @@ -0,0 +1,575 @@ +[MASTER] + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. +extension-pkg-whitelist= + +# Add files or directories to the blacklist. They should be base names, not +# paths. +ignore=CVS + +# Add files or directories matching the regex patterns to the blacklist. The +# regex matches against base names, not paths. +ignore-patterns= + +# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the +# number of processors available to use. +jobs=1 + +# Control the amount of potential inferred values when inferring a single +# object. This can help the performance when dealing with large functions or +# complex, nested conditions. +limit-inference-results=100 + +# Pickle collected data for later comparisons. +persistent=yes + +# When enabled, pylint would attempt to guess common misconfiguration and emit +# user-friendly hints instead of false-positive error messages. +suggestion-mode=yes + +# Allow loading of arbitrary C extensions. Extensions are imported into the +# active Python interpreter and may run arbitrary code. +unsafe-load-any-extension=no + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED. +confidence= + +# Disable the message, report, category or checker with the given id(s). You +# can either give multiple identifiers separated by comma (,) or put this +# option multiple times (only on the command line, not in the configuration +# file where it should appear only once). You can also use "--disable=all" to +# disable everything first and then reenable specific checks. For example, if +# you want to run only the similarities checker, you can use "--disable=all +# --enable=similarities". If you want to run only the classes checker, but have +# no Warning level messages displayed, use "--disable=all --enable=classes +# --disable=W". +disable=print-statement, + parameter-unpacking, + unpacking-in-except, + old-raise-syntax, + backtick, + long-suffix, + old-ne-operator, + old-octal-literal, + import-star-module-level, + non-ascii-bytes-literal, + raw-checker-failed, + bad-inline-option, + locally-disabled, + file-ignored, + suppressed-message, + useless-suppression, + deprecated-pragma, + use-symbolic-message-instead, + apply-builtin, + basestring-builtin, + buffer-builtin, + cmp-builtin, + coerce-builtin, + execfile-builtin, + file-builtin, + long-builtin, + raw_input-builtin, + reduce-builtin, + standarderror-builtin, + unicode-builtin, + xrange-builtin, + coerce-method, + delslice-method, + getslice-method, + setslice-method, + no-absolute-import, + old-division, + dict-iter-method, + dict-view-method, + next-method-called, + metaclass-assignment, + indexing-exception, + raising-string, + reload-builtin, + oct-method, + hex-method, + nonzero-method, + cmp-method, + input-builtin, + round-builtin, + intern-builtin, + unichr-builtin, + map-builtin-not-iterating, + zip-builtin-not-iterating, + range-builtin-not-iterating, + filter-builtin-not-iterating, + using-cmp-argument, + eq-without-hash, + div-method, + idiv-method, + rdiv-method, + exception-message-attribute, + invalid-str-codec, + sys-max-int, + bad-python3-import, + deprecated-string-function, + deprecated-str-translate-call, + deprecated-itertools-function, + deprecated-types-field, + next-method-defined, + dict-items-not-iterating, + dict-keys-not-iterating, + dict-values-not-iterating, + deprecated-operator-function, + deprecated-urllib-function, + xreadlines-attribute, + deprecated-sys-function, + exception-escape, + comprehension-escape, + invalid-name, + no-member, + duplicate-code, + redefined-outer-name + + +# Enable the message, report, category or checker with the given id(s). You can +# either give multiple identifier separated by comma (,) or put this option +# multiple time (only on the command line, not in the configuration file where +# it should appear only once). See also the "--disable" option for examples. +enable=c-extension-no-member + + +[REPORTS] + +# Python expression which should return a score less than or equal to 10. You +# have access to the variables 'error', 'warning', 'refactor', and 'convention' +# which contain the number of messages in each category, as well as 'statement' +# which is the total number of statements analyzed. This score is used by the +# global evaluation report (RP0004). +evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) + +# Template used to display messages. This is a python new-style format string +# used to format the message information. See doc for all details. +#msg-template= + +# Set the output format. Available formats are text, parseable, colorized, json +# and msvs (visual studio). You can also give a reporter class, e.g. +# mypackage.mymodule.MyReporterClass. +output-format=text + +# Tells whether to display a full report or only the messages. +reports=no + +# Activate the evaluation score. +score=yes + + +[REFACTORING] + +# Maximum number of nested blocks for function / method body +max-nested-blocks=5 + +# Complete name of functions that never returns. When checking for +# inconsistent-return-statements if a never returning function is called then +# it will be considered as an explicit return statement and no message will be +# printed. +never-returning-functions=sys.exit + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME, + XXX, + TODO + + +[LOGGING] + +# Format style used to check logging format string. `old` means using % +# formatting, `new` is for `{}` formatting,and `fstr` is for f-strings. +logging-format-style=old + +# Logging modules to check that the string format arguments are in logging +# function parameter format. +logging-modules=logging + + +[TYPECHECK] + +# List of decorators that produce context managers, such as +# contextlib.contextmanager. Add to this list to register other decorators that +# produce valid context managers. +contextmanager-decorators=contextlib.contextmanager + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E1101 when accessed. Python regular +# expressions are accepted. +generated-members= + +# Tells whether missing members accessed in mixin class should be ignored. A +# mixin class is detected if its name ends with "mixin" (case insensitive). +ignore-mixin-members=yes + +# Tells whether to warn about missing members when the owner of the attribute +# is inferred to be None. +ignore-none=yes + +# This flag controls whether pylint should warn about no-member and similar +# checks whenever an opaque object is returned when inferring. The inference +# can return multiple potential results while evaluating a Python object, but +# some branches might not be evaluated, which results in partial inference. In +# that case, it might be useful to still emit no-member and other checks for +# the rest of the inferred objects. +ignore-on-opaque-inference=yes + +# List of class names for which member attributes should not be checked (useful +# for classes with dynamically set attributes). This supports the use of +# qualified names. +ignored-classes=optparse.Values,thread._local,_thread._local + +# List of module names for which member attributes should not be checked +# (useful for modules/projects where namespaces are manipulated during runtime +# and thus existing member attributes cannot be deduced by static analysis). It +# supports qualified module names, as well as Unix pattern matching. +ignored-modules= + +# Show a hint with possible names when a member name was not found. The aspect +# of finding the hint is based on edit distance. +missing-member-hint=yes + +# The minimum edit distance a name should have in order to be considered a +# similar match for a missing member name. +missing-member-hint-distance=1 + +# The total number of similar names that should be taken in consideration when +# showing a hint for a missing member. +missing-member-max-choices=1 + +# List of decorators that change the signature of a decorated function. +signature-mutators= + + +[BASIC] + +# Naming style matching correct argument names. +argument-naming-style=snake_case + +# Regular expression matching correct argument names. Overrides argument- +# naming-style. +#argument-rgx= + +# Naming style matching correct attribute names. +attr-naming-style=snake_case + +# Regular expression matching correct attribute names. Overrides attr-naming- +# style. +#attr-rgx= + +# Bad variable names which should always be refused, separated by a comma. +bad-names=foo, + bar, + baz, + toto, + tutu, + tata + +# Naming style matching correct class attribute names. +class-attribute-naming-style=any + +# Regular expression matching correct class attribute names. Overrides class- +# attribute-naming-style. +#class-attribute-rgx= + +# Naming style matching correct class names. +class-naming-style=PascalCase + +# Regular expression matching correct class names. Overrides class-naming- +# style. +#class-rgx= + +# Naming style matching correct constant names. +const-naming-style=UPPER_CASE + +# Regular expression matching correct constant names. Overrides const-naming- +# style. +#const-rgx= + +# Minimum line length for functions/classes that require docstrings, shorter +# ones are exempt. +docstring-min-length=-1 + +# Naming style matching correct function names. +function-naming-style=snake_case + +# Regular expression matching correct function names. Overrides function- +# naming-style. +#function-rgx= + +# Good variable names which should always be accepted, separated by a comma. +good-names=i, + j, + k, + ex, + Run, + _ + +# Include a hint for the correct naming format with invalid-name. +include-naming-hint=no + +# Naming style matching correct inline iteration names. +inlinevar-naming-style=any + +# Regular expression matching correct inline iteration names. Overrides +# inlinevar-naming-style. +#inlinevar-rgx= + +# Naming style matching correct method names. +method-naming-style=snake_case + +# Regular expression matching correct method names. Overrides method-naming- +# style. +#method-rgx= + +# Naming style matching correct module names. +module-naming-style=snake_case + +# Regular expression matching correct module names. Overrides module-naming- +# style. +#module-rgx= + +# Colon-delimited sets of names that determine each other's naming style when +# the name regexes allow several styles. +name-group= + +# Regular expression which should only match function or class names that do +# not require a docstring. +no-docstring-rgx=^_ + +# List of decorators that produce properties, such as abc.abstractproperty. Add +# to this list to register other decorators that produce valid properties. +# These decorators are taken in consideration only for invalid-name. +property-classes=abc.abstractproperty + +# Naming style matching correct variable names. +variable-naming-style=snake_case + +# Regular expression matching correct variable names. Overrides variable- +# naming-style. +#variable-rgx= + + +[VARIABLES] + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid defining new builtins when possible. +additional-builtins= + +# Tells whether unused global variables should be treated as a violation. +allow-global-unused-variables=yes + +# List of strings which can identify a callback function by name. A callback +# name must start or end with one of those strings. +callbacks=cb_, + _cb + +# A regular expression matching the name of dummy variables (i.e. expected to +# not be used). +dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ + +# Argument names that match this expression will be ignored. Default to name +# with leading underscore. +ignored-argument-names=_.*|^ignored_|^unused_ + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# List of qualified module names which can have objects that can redefine +# builtins. +redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io + + +[SIMILARITIES] + +# Ignore comments when computing similarities. +ignore-comments=yes + +# Ignore docstrings when computing similarities. +ignore-docstrings=yes + +# Ignore imports when computing similarities. +ignore-imports=no + +# Minimum lines number of a similarity. +min-similarity-lines=4 + + +[FORMAT] + +# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. +expected-line-ending-format= + +# Regexp for a line that is allowed to be longer than the limit. +ignore-long-lines=^\s*(# )??$ + +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren=4 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' + +# Maximum number of characters on a single line. +max-line-length=100 + +# Maximum number of lines in a module. +max-module-lines=1000 + +# List of optional constructs for which whitespace checking is disabled. `dict- +# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. +# `trailing-comma` allows a space between comma and closing bracket: (a, ). +# `empty-line` allows space-only lines. +no-space-check=trailing-comma, + dict-separator + +# Allow the body of a class to be on the same line as the declaration if body +# contains single statement. +single-line-class-stmt=no + +# Allow the body of an if to be on the same line as the test if there is no +# else. +single-line-if-stmt=no + + +[STRING] + +# This flag controls whether the implicit-str-concat-in-sequence should +# generate a warning on implicit string concatenation in sequences defined over +# several lines. +check-str-concat-over-line-jumps=no + + +[SPELLING] + +# Limits count of emitted suggestions for spelling mistakes. +max-spelling-suggestions=4 + +# Spelling dictionary name. Available dictionaries: none. To make it work, +# install the python-enchant package. +spelling-dict= + +# List of comma separated words that should not be checked. +spelling-ignore-words= + +# A path to a file that contains the private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to the private dictionary (see the +# --spelling-private-dict-file option) instead of raising a message. +spelling-store-unknown-words=no + + +[DESIGN] + +# Maximum number of arguments for function / method. +max-args=5 + +# Maximum number of attributes for a class (see R0902). +max-attributes=7 + +# Maximum number of boolean expressions in an if statement (see R0916). +max-bool-expr=5 + +# Maximum number of branch for function / method body. +max-branches=12 + +# Maximum number of locals for function / method body. +max-locals=15 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=20 + +# Maximum number of return / yield for function / method body. +max-returns=6 + +# Maximum number of statements in function / method body. +max-statements=50 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=2 + + +[CLASSES] + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__, + __new__, + setUp, + __post_init__ + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict, + _fields, + _replace, + _source, + _make + +# List of valid names for the first argument in a class method. +valid-classmethod-first-arg=cls + +# List of valid names for the first argument in a metaclass class method. +valid-metaclass-classmethod-first-arg=cls + + +[IMPORTS] + +# List of modules that can be imported at any level, not just the top level +# one. +allow-any-import-level= + +# Allow wildcard imports from modules that define __all__. +allow-wildcard-with-all=no + +# Analyse import fallback blocks. This can be used to support both Python 2 and +# 3 compatible code, which means that the block might have code that exists +# only in one or another interpreter, leading to false positives when analysed. +analyse-fallback-blocks=no + +# Deprecated modules which should not be used, separated by a comma. +deprecated-modules=optparse,tkinter.tix + +# Create a graph of external dependencies in the given file (report RP0402 must +# not be disabled). +ext-import-graph= + +# Create a graph of every (i.e. internal and external) dependencies in the +# given file (report RP0402 must not be disabled). +import-graph= + +# Create a graph of internal dependencies in the given file (report RP0402 must +# not be disabled). +int-import-graph= + +# Force import order to recognize a module as part of the standard +# compatibility libraries. +known-standard-library= + +# Force import order to recognize a module as part of a third party library. +known-third-party=enchant + +# Couples of modules and preferred modules, separated by a comma. +preferred-modules= + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when being caught. Defaults to +# "BaseException, Exception". +overgeneral-exceptions=BaseException, + Exception diff --git a/examples/blocks_list.py b/examples/blocks_list.py index ca90cce1..daab435c 100755 --- a/examples/blocks_list.py +++ b/examples/blocks_list.py @@ -1,17 +1,19 @@ #!/usr/bin/env python - +""" +Retrieve list of blocked items +""" from __future__ import print_function import pyslurm -from time import gmtime, strftime -def display(block_dict): +def display(block_dict): + """Format output""" if block_dict: - date_fields = [ ] + date_fields = [] - print('{0:*^80}'.format('')) + print("{0:*^80}".format("")) for key, value in block_dict.items(): @@ -22,19 +24,23 @@ def display(block_dict): ddate = value[part_key] if ddate == 0: print("\t{0:<17} : N/A".format(part_key)) - elif ('reason_uid' in part_key) and (value['reason'] is None): + elif ("reason_uid" in part_key) and (value["reason"] is None): print("\t{0:<17} :".format(part_key)) else: ddate = pyslurm.epoch2date(ddate) print("\t{0:<17} : {1}".format(part_key, ddate)) - elif part_key == 'connection_type': - print("\t{0:<17} : {1}".format(part_key, pyslurm.get_connection_type(value[part_key]))) - elif part_key == 'state': + elif part_key == "connection_type": + print( + "\t{0:<17} : {1}".format( + part_key, pyslurm.get_connection_type(value[part_key]) + ) + ) + elif part_key == "state": print("\t{0:<17} : {1}".format(part_key, value[part_key])) else: print("\t{0:<17} : {1}".format(part_key, value[part_key])) - print('{0:*^80}'.format('')) + print("{0:*^80}".format("")) if __name__ == "__main__": @@ -43,15 +49,11 @@ def display(block_dict): try: a.load() block_dict = a.get() - except ValueError as e: - print("Block query failed - {0}".format(e.args[0])) + except ValueError as value_error: + print("Block query failed - {0}".format(value_error.args[0])) else: - if len(block_dict) > 0: - + if block_dict: display(block_dict) - print() - print("Block IDs - {0}".format(a.ids())) - print() - + print("\nBlock IDs - {0}\n".format(a.ids())) else: print("No Blocks found !") diff --git a/examples/blocks_list2.py b/examples/blocks_list2.py index d08f1f3e..e463c22e 100755 --- a/examples/blocks_list2.py +++ b/examples/blocks_list2.py @@ -1,13 +1,15 @@ #!/usr/bin/env python - +""" +Retrieve list of blocked items +""" from __future__ import print_function -import pyslurm -import sys from time import sleep -class DictDiffer(object): +import pyslurm + +class DictDiffer: """ http://stackoverflow.com/questions/1165352/fast-comparison-between-two-python-dictionary @@ -16,20 +18,37 @@ class DictDiffer(object): (2) items removed (3) keys same in both but changed values (4) keys same in both and unchanged values - """ + """ def __init__(self, current_dict, past_dict): + """set class attr""" self.current_dict, self.past_dict = current_dict, past_dict - self.set_current, self.set_past = set(current_dict.keys()), set(past_dict.keys()) + self.set_current, self.set_past = ( + set(current_dict.keys()), + set(past_dict.keys()), + ) self.intersect = self.set_current.intersection(self.set_past) + def added(self): + """Check if added""" return self.set_current - self.intersect + def removed(self): + """Check if removed""" return self.set_past - self.intersect + def changed(self): - return set(o for o in self.intersect if self.past_dict[o] != self.current_dict[o]) + """Check if changed""" + return set( + o for o in self.intersect if self.past_dict[o] != self.current_dict[o] + ) + def unchanged(self): - return set(o for o in self.intersect if self.past_dict[o] == self.current_dict[o]) + """Check for no change""" + return set( + o for o in self.intersect if self.past_dict[o] == self.current_dict[o] + ) + if __name__ == "__main__": @@ -45,14 +64,17 @@ def unchanged(self): sleep(0.5) - while 1: - + while True: new_dict = a.get() newUpdate = a.lastUpdate() if newUpdate > lastUpdate: lastUpdate = a.lastUpdate() - print("Block data update time changed - {0}".format(pyslurm.epoch2date(lastUpdate))) + print( + "Block data update time changed - {0}".format( + pyslurm.epoch2date(lastUpdate) + ) + ) b = DictDiffer(block_dict, new_dict) if b.changed(): @@ -64,13 +86,9 @@ def unchanged(self): if b.removed(): print("\tRemoved block {0}".format(b.removed())) change = 1 - if change == 0: print("\tBut no data was changed !") change = 0 - block_dict = new_dict sleep(interval) - - sys.exit() diff --git a/examples/cancel_job.py b/examples/cancel_job.py index 6f7ec687..e8670e0e 100755 --- a/examples/cancel_job.py +++ b/examples/cancel_job.py @@ -1,12 +1,14 @@ #!/usr/bin/env python - +""" +Cancel a scheduled job +""" from __future__ import print_function import pyslurm try: rc = pyslurm.slurm_kill_job(51, 9, 0) -except ValueError as e: - print("Cancel job error - {0}".format(e.args[0])) +except ValueError as value_error: + print("Cancel job error - {0}".format(value_error.args[0])) else: print("Success - cancelled job") diff --git a/examples/checkpoint_job.py b/examples/checkpoint_job.py index 30d2c4d2..a7bc4862 100755 --- a/examples/checkpoint_job.py +++ b/examples/checkpoint_job.py @@ -1,12 +1,14 @@ #!/usr/bin/env python - +""" +Retrieve a jobs checkpoint status +""" from __future__ import print_function import pyslurm try: - time = pyslurm.slurm_checkpoint_able(2,0) -except ValueError as e: - print("Checkpointable job failed - {0}".format(e.args[0])) + time = pyslurm.slurm_checkpoint_able(2, 0) +except ValueError as value_error: + print("Checkpointable job failed - {0}".format(value_error.args[0])) else: print("Job can be checkpointed at {0}".format(time)) diff --git a/examples/controllers.py b/examples/controllers.py index c66734a8..8648943d 100755 --- a/examples/controllers.py +++ b/examples/controllers.py @@ -1,20 +1,24 @@ #!/usr/bin/env python - +""" +Retrieve list up Slurm controllers +""" from __future__ import print_function -import pyslurm import socket -import sys -def controller_up(controller=1): +import pyslurm + +def controller_up(controller=1): + """Check if controller up via ping""" try: pyslurm.slurm_ping(controller) - except valueError as e: - print("Failed - {0}".format(e.args[0])) + except ValueError as value_error: + print("Failed - {0}".format(value_error.args[0])) else: print("Success") + if __name__ == "__main__": print() @@ -37,11 +41,11 @@ def controller_up(controller=1): print("\nPinging SLURM controllers") if primary: - print("\tPrimary .....", end=' ') + print("\tPrimary .....", end=" ") controller_up() if backup: - print("\tBackup .....", end=' ') + print("\tBackup .....", end=" ") controller_up(2) - except ValueError as e: - print("Error - {0}".format(e.args[0])) + except ValueError as value_error: + print("Error - {0}".format(value_error.args[0])) diff --git a/examples/debug_levels.py b/examples/debug_levels.py index 65d4d5a5..00472e51 100755 --- a/examples/debug_levels.py +++ b/examples/debug_levels.py @@ -1,24 +1,26 @@ #!/usr/bin/env python - +""" +How to set Slurm debug level +""" from __future__ import print_function import pyslurm -SLURM_DEBUG=1 -SCHED_DEBUG=0 +SLURM_DEBUG = 1 +SCHED_DEBUG = 0 try: print("Setting Slurmd debug level to {0}".format(SLURM_DEBUG)) rc = pyslurm.slurm_set_debug_level(SLURM_DEBUG) if rc == 0: print("\tSuccess...Slurmd debug level updated to {0}".format(SLURM_DEBUG)) -except ValueError as e: - print("\tError - {0}".format(e.args[0])) +except ValueError as value_error: + print("\tError - {0}".format(value_error.args[0])) try: print("Setting Schedlog debug level to {0}".format(SCHED_DEBUG)) rc = pyslurm.slurm_set_schedlog_level(SCHED_DEBUG) if rc == 0: print("\tSuccess...Schedlog log level updated to {0}".format(SCHED_DEBUG)) -except ValueError as e: - print("\tError - {0}".format(e.args[0])) +except ValueError as value_error: + print("\tError - {0}".format(value_error.args[0])) diff --git a/examples/hostlist.py b/examples/hostlist.py index bdcfeb65..4709285d 100755 --- a/examples/hostlist.py +++ b/examples/hostlist.py @@ -1,5 +1,7 @@ #!/usr/bin/env python - +""" +Retrieve Slurm hosts +""" from __future__ import print_function import pyslurm @@ -9,7 +11,6 @@ hosts = "dummy0,dummy1,dummy1,dummy3,dummy4" print("Creating hostlist ...... with {0}".format(hosts)) if b.create(hosts): - print() print("\tHost list count is {0}".format(b.count())) node = "dummy3" diff --git a/examples/job_test.py b/examples/job_test.py index 02e9a249..8711b5a3 100755 --- a/examples/job_test.py +++ b/examples/job_test.py @@ -1,5 +1,7 @@ #!/usr/bin/env python - +""" +Class to access/modify Slurm Job Information. +""" from __future__ import print_function import pyslurm @@ -7,7 +9,7 @@ try: a = pyslurm.job() - jobs = a.get() + jobs = a.get() print(jobs) -except ValueError as e: - print("Job list error - {0}".format(e.args[0])) +except ValueError as value_error: + print("Job list error - {0}".format(value_error.args[0])) diff --git a/examples/jobs_list.py b/examples/jobs_list.py index ec59b200..15c9b777 100755 --- a/examples/jobs_list.py +++ b/examples/jobs_list.py @@ -1,23 +1,25 @@ #!/usr/bin/env python - +""" +List Slurm jobs +""" from __future__ import print_function import pyslurm -import sys -from time import gmtime, strftime, sleep def display(job_dict): - + """Format output""" if job_dict: - time_fields = ['time_limit'] + time_fields = ["time_limit"] - date_fields = ['start_time', - 'submit_time', - 'end_time', - 'eligible_time', - 'resize_time'] + date_fields = [ + "start_time", + "submit_time", + "end_time", + "eligible_time", + "resize_time", + ] for key, value in sorted(job_dict.items()): @@ -40,13 +42,14 @@ def display(job_dict): print("-" * 80) + if __name__ == "__main__": try: a = pyslurm.job() jobs = a.get() - if len(jobs) > 0: + if jobs: display(jobs) @@ -54,9 +57,9 @@ def display(job_dict): print("Number of Jobs - {0}".format(len(jobs))) print() - pending = a.find('job_state', 'PENDING') - running = a.find('job_state', 'RUNNING') - held = a.find('job_state', 'RUNNING') + pending = a.find("job_state", "PENDING") + running = a.find("job_state", "RUNNING") + held = a.find("job_state", "RUNNING") print("Number of pending jobs - {0}".format(len(pending))) print("Number of running jobs - {0}".format(len(running))) @@ -68,5 +71,5 @@ def display(job_dict): else: print("No jobs found !") - except ValueError as e: - print("Job query failed - {0}".format(e.args[0])) + except ValueError as value_error: + print("Job query failed - {0}".format(value_error.args[0])) diff --git a/examples/jobsteps_layout.py b/examples/jobsteps_layout.py index 360ee2c5..43d5e964 100755 --- a/examples/jobsteps_layout.py +++ b/examples/jobsteps_layout.py @@ -1,13 +1,15 @@ #!/usr/bin/env python - +""" +Display Slurm jobsteps +""" from __future__ import print_function import pyslurm -def display(steps): - time_fields = ['time_limit'] - date_fields = ['start_time'] +def display(steps): + """Format output""" + date_fields = ["start_time"] for job, job_step in sorted(steps.items()): @@ -27,10 +29,11 @@ def display(steps): else: print("\t\t{0:<20} : {1}".format(task, value)) + if __name__ == "__main__": a = pyslurm.jobstep() steps = a.get() - if len(steps) > 0: + if steps: display(steps) diff --git a/examples/jobsteps_list.py b/examples/jobsteps_list.py index 99571995..14864c37 100755 --- a/examples/jobsteps_list.py +++ b/examples/jobsteps_list.py @@ -1,35 +1,30 @@ #!/usr/bin/env python - +""" +List steps jobs have gone through +""" from __future__ import print_function import pyslurm -import sys -from time import gmtime, strftime steps = pyslurm.jobstep() a = steps.get() if a: for job, job_step in sorted(a.items()): - - print("Job: {0}".format(job)) for step, step_data in sorted(job_step.items()): - print("\tStep: {0}".format(step)) for step_item, item_data in sorted(step_data.items()): - - if 'start_time' in step_item: + if "start_time" in step_item: ddate = pyslurm.epoch2date(item_data) print("\t\t{0:<15} : {1}".format(step_item, ddate)) else: print("\t\t{0:<15} : {1}".format(step_item, item_data)) - layout = steps.layout(job, step) print("\t\tLayout:") for name, value in sorted(layout.items()): print("\t\t\t{0:<15} : {1}".format(name, value)) - print('{0:*^80}'.format('')) + print("{0:*^80}".format("")) else: print("No jobsteps found !") diff --git a/examples/licenses.py b/examples/licenses.py index c7655bd7..11bf8921 100755 --- a/examples/licenses.py +++ b/examples/licenses.py @@ -1,24 +1,29 @@ #!/usr/bin/env python - +""" +List Slurm licenses +""" from __future__ import print_function -def display(lic_dict): +def display(lic_dict): + """Format output""" if lic_dict: - print("State last updated : {0}".format(slurm.epoch2date(licenses.lastUpdate()))) - print('{0:*^80}'.format('')) + print( + "State last updated : {0}".format(slurm.epoch2date(licenses.lastUpdate())) + ) + print("{0:*^80}".format("")) for key, value in lic_dict.items(): print("{0} :".format(key)) for part_key in sorted(value.keys()): - print("\t{0:<17} : {1}".format(part_key, value[part_key])) - print('{0:*^80}'.format('')) + print("{0:*^80}".format("")) else: print("No Licenses found !") + if __name__ == "__main__": import pyslurm as slurm @@ -33,17 +38,17 @@ def display(lic_dict): new = old display(lic) - while 1: + while True: time.sleep(1) lic = licenses.get() new = licenses.lastUpdate() if new > old: - old = new - print('{0:*^80}'.format('')) + old = new + print("{0:*^80}".format("")) display(lic) - print('{0:*^80}'.format('')) - except ValueError as e: - print("License error : {0}".format(e.args[0])) + print("{0:*^80}".format("")) + except ValueError as value_error: + print("License error : {0}".format(value_error.args[0])) sys.exit(-1) except KeyboardInterrupt: print("Exiting....") diff --git a/examples/listdb_cluster.py b/examples/listdb_cluster.py index aca8cc86..c2b4f548 100755 --- a/examples/listdb_cluster.py +++ b/examples/listdb_cluster.py @@ -1,12 +1,16 @@ #!/usr/bin/env python - -import time as tm +""" +List clusters +""" from datetime import datetime + import pyslurm -def cluster_display( cluster ): - for key,value in cluster.items(): - if key == 'accounting': + +def cluster_display(cluster): + """Format output""" + for key, value in cluster.items(): + if key == "accounting": print("\t accounting {") for acct_key, acct_value in value.items(): print("\t\t{}={}".format(acct_key, acct_value)) @@ -14,21 +18,21 @@ def cluster_display( cluster ): else: print("\t{}={}".format(key, value)) + if __name__ == "__main__": try: - start = (datetime(2016,12,1) - datetime(1970,1,1)).total_seconds() - end = (datetime(2016,12,2) - datetime(1970,1,1)).total_seconds() - 1 - print("start={}, end={}".format(start,end)) + start = (datetime(2016, 12, 1) - datetime(1970, 1, 1)).total_seconds() + end = (datetime(2016, 12, 2) - datetime(1970, 1, 1)).total_seconds() - 1 + print("start={}, end={}".format(start, end)) clusters = pyslurm.slurmdb_clusters() - print(clusters.set_cluster_condition(start,end)) + print(clusters.set_cluster_condition(start, end)) clusters_dict = clusters.get() - if len(clusters_dict): + if clusters_dict: for key, value in clusters_dict.items(): - print("{} Clusters: {}".format('{',key)) - cluster_display( value) + print("{} Clusters: {}".format("{", key)) + cluster_display(value) print("}") else: print("No cluster found --") except ValueError as e: print("Error:{}".format(e.args[0])) - diff --git a/examples/listdb_events.py b/examples/listdb_events.py index f0e2af45..963d76f5 100755 --- a/examples/listdb_events.py +++ b/examples/listdb_events.py @@ -1,41 +1,46 @@ #!/usr/bin/env python - +""" +List Slurm events +""" +import sys import time from datetime import datetime -import sys + import pyslurm + def event_display(event): - for key,value in event.items(): - if (key == "time_start") or (key == "time_end") : - print ("\t{}={} <-> {}".format(key, value, datetime.fromtimestamp(value))) - else : - print ("\t{}={}".format(key, value)) + """Format output""" + for key, value in event.items(): + if (key == "time_start") or (key == "time_end"): + print("\t{}={} <-> {}".format(key, value, datetime.fromtimestamp(value))) + else: + print("\t{}={}".format(key, value)) + if __name__ == "__main__": try: - if len(sys.argv) != 3 : + if len(sys.argv) != 3: print("usage: python listdb_events.py start-tme end-time") print("(format: yyyy-mm-dd)") - exit(1) + sys.exit(1) - start = time.mktime(time.strptime(sys.argv[1], '%Y-%m-%d')) - end = time.mktime(time.strptime(sys.argv[2], '%Y-%m-%d')) + start = time.mktime(time.strptime(sys.argv[1], "%Y-%m-%d")) + end = time.mktime(time.strptime(sys.argv[2], "%Y-%m-%d")) print("start={}, end={}".format(start, end)) events = pyslurm.slurmdb_events() events.set_event_condition(start, end) events_dict = events.get() ii = 0 - if len(events_dict): + if events_dict: for key, value in events_dict.items(): - d = int(value['time_end']) - int(value['time_start']) - ii +=1 + d = int(value["time_end"]) - int(value["time_start"]) + ii += 1 print("{") event_display(value) print("}") else: print("No event found") - except ValueError as e: - print("Error:{}".format(e.args[0])) - + except ValueError as value_error: + print("Error:{}".format(value_error.args[0])) diff --git a/examples/listdb_jobs.py b/examples/listdb_jobs.py index b67c5765..204e7657 100755 --- a/examples/listdb_jobs.py +++ b/examples/listdb_jobs.py @@ -1,26 +1,31 @@ #!/usr/bin/env python - +""" +List all jobs in Slurm, similar to `sacct` +""" import time + import pyslurm -def job_display( job ): - for key,value in job.items(): + +def job_display(job): + """Format output""" + for key, value in job.items(): print("\t{}={}".format(key, value)) + if __name__ == "__main__": try: end = time.time() - start = end - (30*24*60*60) - print("start={}, end={}".format(start,end)) + start = end - (30 * 24 * 60 * 60) + print("start={}, end={}".format(start, end)) jobs = pyslurm.slurmdb_jobs() jobs_dict = jobs.get(starttime=start, endtime=end) - if len(jobs_dict): + if jobs_dict: for key, value in jobs_dict.items(): - print("{} Job: {}".format('{',key)) + print("{} Job: {}".format("{", key)) job_display(value) print("}") else: print("No job found") - except ValueError as e: - print("Error:{}".format(e.args[0])) - + except ValueError as job_exception: + print("Error:{}".format(job_exception.args[0])) diff --git a/examples/listdb_qos.py b/examples/listdb_qos.py index a6202a7c..612cb054 100755 --- a/examples/listdb_qos.py +++ b/examples/listdb_qos.py @@ -1,14 +1,16 @@ #!/usr/bin/env python - +""" +List Slurm QOS +""" import pyslurm if __name__ == "__main__": try: - qos_dict = pyslurm.qos().get() - if len(qos_dict): - for key, value in qos_dict.items(): + qosDict = pyslurm.qos().get() + if qosDict: + for key, value in qosDict.items(): print("{") - if type(value) is dict: + if isinstance(value, dict): print("\t{}=".format(key)) for k, v in value.items(): print("\t\t{}={}".format(k, v)) @@ -17,6 +19,5 @@ print("}") else: print("No QOS found") - except ValueError as e: - print("Error:{}".format(e.args[0])) - + except ValueError as qos_exception: + print("Error:{}".format(qos_exception.args[0])) diff --git a/examples/listdb_reservations.py b/examples/listdb_reservations.py index d4c95d28..106f9124 100755 --- a/examples/listdb_reservations.py +++ b/examples/listdb_reservations.py @@ -1,28 +1,33 @@ #!/usr/bin/env python - +""" +List Slurm reservations +""" import time + import pyslurm + def reservation_display(reservation): + """Format output""" if reservation: - for key,value in reservation.items(): - print("\t{}={}".format(key, value)) + for key, value in reservation.items(): + print("\t{}={}".format(key, value)) + if __name__ == "__main__": try: end = time.time() - start = end - (30*24*60*60) + start = end - (30 * 24 * 60 * 60) print("start={}, end={}".format(start, end)) reservations = pyslurm.slurmdb_reservations() reservations.set_reservation_condition(start, end) reservations_dict = reservations.get() - if len(reservations_dict): + if reservations_dict: for key, value in reservations_dict.items(): - print("{} Reservation: {}".format('{', key)) + print("{} Reservation: {}".format("{", key)) reservation_display(value) print("}") else: print("No reservation found") - except ValueError as e: - print("Error:{}".format(e.args[0])) - + except ValueError as db_exception: + print("Error:{}".format(db_exception.args[0])) diff --git a/examples/node_list.py b/examples/node_list.py index 4bd0457d..886b6339 100755 --- a/examples/node_list.py +++ b/examples/node_list.py @@ -1,14 +1,17 @@ #!/usr/bin/env python - +""" +List Slurm nodes +""" from __future__ import print_function -def display(node_dict): +def display(node_dict): + """Format output""" if node_dict: - date_fields = [ 'boot_time', 'slurmd_start_time', 'last_update', 'reason_time' ] + date_fields = ["boot_time", "slurmd_start_time", "last_update", "reason_time"] - print('{0:*^80}'.format('')) + print("{0:*^80}".format("")) for key, value in node_dict.items(): print("{0} :".format(key)) @@ -21,12 +24,13 @@ def display(node_dict): else: ddate = pyslurm.epoch2date(ddate) print("\t{0:<17} : {1}".format(part_key, ddate)) - elif ('reason_uid' in part_key and value['reason'] is None): + elif "reason_uid" in part_key and value["reason"] is None: print("\t{0:<17} : ".format(part_key[0])) else: print("\t{0:<17} : {1}".format(part_key[0], part_key[1])) - print('{0:*^80}'.format('')) + print("{0:*^80}".format("")) + if __name__ == "__main__": @@ -36,13 +40,10 @@ def display(node_dict): Nodes = pyslurm.node() node_dict = Nodes.get() - if len(node_dict) > 0: - + if node_dict: display(node_dict) - print() print("Node IDs - {0}".format(Nodes.ids())) - else: print("No Nodes found !") diff --git a/examples/node_update.py b/examples/node_update.py index 0c359106..e89512f2 100755 --- a/examples/node_update.py +++ b/examples/node_update.py @@ -1,6 +1,6 @@ #!/usr/bin/env python - -"""Modify the state of a Node or BG Base Partition +""" +Modify the state of a Node or BG Base Partition Valid States : @@ -20,10 +20,10 @@ import pyslurm Node_dict = { - 'node_names': 'c10', - 'node_state': pyslurm.NODE_STATE_DRAIN, - 'reason': 'API test' - } + "node_names": "c10", + "node_state": pyslurm.NODE_STATE_DRAIN, + "reason": "API test", +} try: a = pyslurm.node() diff --git a/examples/partition_create.py b/examples/partition_create.py index bde70257..aa307893 100755 --- a/examples/partition_create.py +++ b/examples/partition_create.py @@ -1,19 +1,21 @@ #!/usr/bin/env python - +""" +Create a slurm partition. +""" from __future__ import print_function import pyslurm a = pyslurm.partition() partition_dict = pyslurm.create_partition_dict() -partition_dict['Name'] ='part_test' +partition_dict["Name"] = "part_test" try: a.create(partition_dict) except ValueError as e: print("Partition create failed - {0}".format(e.args[0])) else: - print("Partition {0} successfully created".format(partition_dict['Name'])) + print("Partition {0} successfully created".format(partition_dict["Name"])) a.get() print() diff --git a/examples/partition_delete.py b/examples/partition_delete.py index f78dba55..801e092f 100755 --- a/examples/partition_delete.py +++ b/examples/partition_delete.py @@ -1,5 +1,7 @@ #!/usr/bin/env python - +""" +Delete a given slurm partition +""" from __future__ import print_function import pyslurm diff --git a/examples/partition_list.py b/examples/partition_list.py index 4874cf09..d2c96940 100755 --- a/examples/partition_list.py +++ b/examples/partition_list.py @@ -1,10 +1,13 @@ #!/usr/bin/env python - +""" +List Slurm partitions +""" from __future__ import print_function -def display(part_dict): - if len(part_dict) > 0: +def display(part_dict): + """Format output""" + if part_dict: for key, value in part_dict.items(): @@ -14,26 +17,26 @@ def display(part_dict): valStr = value[part_key] - if 'default_time' in part_key: + if "default_time" in part_key: if isinstance(value[part_key], int): - valStr = "{0} minutes".format(value[part_key]/60) + valStr = "{0} minutes".format(value[part_key] / 60) else: valStr = value[part_key] - elif part_key in [ 'max_nodes', 'max_time', 'max_cpus_per_node']: + elif part_key in ["max_nodes", "max_time", "max_cpus_per_node"]: if value[part_key] == "UNLIMITED": valStr = "Unlimited" print("\t{0:<20} : {1}".format(part_key, valStr)) - print('{0:*^80}'.format('')) + print("{0:*^80}".format("")) + if __name__ == "__main__": import pyslurm - import time try: a = pyslurm.partition() @@ -41,10 +44,8 @@ def display(part_dict): except ValueError as e: print("Partition error - {0}".format(e.args[0])) else: - if len(part_dict) > 0: - + if part_dict: display(part_dict) - print() print("Partition IDs - {0}".format(a.ids())) print() diff --git a/examples/partition_update.py b/examples/partition_update.py index 34ea5e5a..3d24236f 100755 --- a/examples/partition_update.py +++ b/examples/partition_update.py @@ -1,14 +1,16 @@ #!/usr/bin/env python - +""" +Update a given Slurm partitions +""" from __future__ import print_function import pyslurm part_dict = pyslurm.create_partition_dict() -part_dict['Name'] = 'part_test' -part_dict['State'] = 'DOWN' -part_dict['Reason'] = 'API test' +part_dict["Name"] = "part_test" +part_dict["State"] = "DOWN" +part_dict["Reason"] = "API test" try: a = pyslurm.slurm_update_partition(part_dict) diff --git a/examples/reservation_create.py b/examples/reservation_create.py index 48797911..549fbe3a 100755 --- a/examples/reservation_create.py +++ b/examples/reservation_create.py @@ -1,11 +1,14 @@ #!/usr/bin/env python - +""" +Create a Slurm reservation +""" from __future__ import print_function -import pyslurm import sys import time +import pyslurm + epoch_now = int(time.time()) a = pyslurm.reservation() @@ -18,15 +21,15 @@ try: resid = a.create(res_dict) -except ValueError as e: - print("Reservation creation failed - {0}".format(e.args[0])) +except ValueError as value_error: + print("Reservation creation failed - {0}".format(value_error.args[0])) else: print("Success - Created reservation {0}\n".format(resid)) res_dict = a.get() if res_dict.get(resid): - date_fields = [ 'end_time', 'start_time' ] + date_fields = ["end_time", "start_time"] value = res_dict[resid] print("Res ID : {0}".format(resid)) @@ -40,15 +43,15 @@ ddate = pyslurm.epoch2date(value[res_key]) print("\t{0:<20} : {1}".format(res_key, ddate)) else: - print("\t{0:<20} : {1}".format(res_key, value[res_key])) + print("\t{0:<20} : {1}".format(res_key, value[res_key])) - print('{0:-^80}'.format('')) + print("{0:-^80}".format("")) else: print("No reservation {0} found !".format(resid)) sys.exit(-1) print() - print('{0:-^80}'.format(' All Reservations ')) + print("{0:-^80}".format(" All Reservations ")) a.print_reservation_info_msg() - print('{0:-^80}'.format('')) + print("{0:-^80}".format("")) diff --git a/examples/reservation_delete.py b/examples/reservation_delete.py index 22817fed..24f85dab 100755 --- a/examples/reservation_delete.py +++ b/examples/reservation_delete.py @@ -1,5 +1,7 @@ #!/usr/bin/env python - +""" +Delete Slurm reservations +""" from __future__ import print_function import pyslurm @@ -7,7 +9,7 @@ resName = "res_test" try: rc = pyslurm.slurm_delete_reservation(resName) -except ValueError as e: - print("Reservation ({0}) delete failed - {1}".format(resName, e.args[0])) +except ValueError as value_error: + print("Reservation ({0}) delete failed - {1}".format(resName, value_error.args[0])) else: print("Reservation {0} deleted".format(resName)) diff --git a/examples/reservation_list.py b/examples/reservation_list.py index b8221bb1..e8a9c6e4 100755 --- a/examples/reservation_list.py +++ b/examples/reservation_list.py @@ -1,16 +1,19 @@ #!/usr/bin/env python - +""" +List Slurm reservations +""" from __future__ import print_function -import pyslurm -import datetime import time -def display(res_dict): +import pyslurm - if len(res_dict) > 0: - date_fields = ['end_time', 'start_time'] +def display(res_dict): + """Format output""" + if res_dict: + + date_fields = ["end_time", "start_time"] for key, value in res_dict.items(): @@ -25,18 +28,19 @@ def display(res_dict): ddate = pyslurm.epoch2date(value[res_key]) print("\t{0:<20} : {1}".format(res_key, ddate)) else: - print("\t{0:<20} : {1}".format(res_key, value[res_key])) + print("\t{0:<20} : {1}".format(res_key, value[res_key])) - print('{0:*^80}'.format('')) + print("{0:*^80}".format("")) now = int(time.time()) resvState = "INACTIVE" - if value['start_time'] <= now and value['end_time'] >= now: + if value["start_time"] <= now <= value["end_time"]: resvState = "ACTIVE" print("\t%-20s : %s\n" % ("state", resvState)) + if __name__ == "__main__": try: @@ -48,5 +52,5 @@ def display(res_dict): print("Res IDs - {0}".format(a.ids())) else: print("No reservations found !") - except ValueError as e: - print("Error - {0}".format(e.args[0])) + except ValueError as value_error: + print("Error - {0}".format(value_error.args[0])) diff --git a/examples/reservation_update.py b/examples/reservation_update.py index 4b942f74..420ab903 100755 --- a/examples/reservation_update.py +++ b/examples/reservation_update.py @@ -1,5 +1,7 @@ #!/usr/bin/env python - +""" +Update Slurm reservations +""" from __future__ import print_function import pyslurm @@ -13,7 +15,7 @@ a.update(res_dict) -except ValueError as e: - printl("Error - {0}".format(e.args[0])) +except ValueError as value_error: + print("Error - {0}".format(value_error.args[0])) else: print("Reservation {0} updated".format(res_dict["name"])) diff --git a/examples/show-cluster-util.py b/examples/show-cluster-util.py index 7ed7683e..06906c56 100755 --- a/examples/show-cluster-util.py +++ b/examples/show-cluster-util.py @@ -1,38 +1,41 @@ #!/usr/bin/env python - +""" +Print cluster utilization. +""" from __future__ import print_function -import pyslurm import sys +import pyslurm + def human_readable(num, suffix="B"): """Convert bytes to a human readable form""" if num == 0: return "0.0 GB" - else: - for unit in ['', 'K', 'M', 'G', 'T', 'P']: - if abs(num) < 1024.0: - return "%.1f %s%s" % (num, unit, suffix) - num /= 1024.0 + for unit in ["", "K", "M", "G", "T", "P"]: + if abs(num) < 1024.0: + return "%.1f %s%s" % (num, unit, suffix) + num /= 1024.0 def get_util(nodes): - """ Return a tuple of cpu and memory percent values. - """ - all_metrics = {"total_cpus_alloc": 0, - "total_cpus_idle": 0, - "total_cpus_down": 0, - "total_cpus_config": 0, - "total_memory_alloc": 0, - "total_memory_idle": 0, - "total_memory_down": 0, - "total_memory_config": 0, - "total_nodes_mixed": 0, - "total_nodes_alloc": 0, - "total_nodes_idle": 0, - "total_nodes_down": 0, - "total_nodes_config": 0} + """ Return a tuple of cpu and memory percent values.""" + all_metrics = { + "total_cpus_alloc": 0, + "total_cpus_idle": 0, + "total_cpus_down": 0, + "total_cpus_config": 0, + "total_memory_alloc": 0, + "total_memory_idle": 0, + "total_memory_down": 0, + "total_memory_config": 0, + "total_nodes_mixed": 0, + "total_nodes_alloc": 0, + "total_nodes_idle": 0, + "total_nodes_down": 0, + "total_nodes_config": 0, + } for node in nodes: nodeinfo = nodes.get(node) @@ -53,10 +56,10 @@ def get_util(nodes): all_metrics["total_memory_down"] += memory_real else: all_metrics["total_cpus_alloc"] += cpus_alloc - all_metrics["total_cpus_idle"] += (cpus_total - cpus_alloc) + all_metrics["total_cpus_idle"] += cpus_total - cpus_alloc all_metrics["total_memory_alloc"] += memory_alloc - all_metrics["total_memory_idle"] += (memory_real - memory_alloc) + all_metrics["total_memory_idle"] += memory_real - memory_alloc if "ALLOCATED" in state: all_metrics["total_nodes_alloc"] += 1 @@ -69,7 +72,8 @@ def get_util(nodes): def display_metrics(metrics): - """ Print cluster utilization. + """ + Print cluster utilization. IN: (dict) dictionary of all node, cpu and memory states """ @@ -78,36 +82,68 @@ def display_metrics(metrics): print("Total Mixed Nodes : {0:>8}".format(metrics["total_nodes_mixed"])) print("Total Idle Nodes : {0:>8}".format(metrics["total_nodes_idle"])) print("Total Down Nodes : {0:>8}".format(metrics["total_nodes_down"])) - print("Total Eligible Nodes : {0:>8}".format(metrics["total_nodes_config"] - - metrics["total_nodes_down"])) + print( + "Total Eligible Nodes : {0:>8}".format( + metrics["total_nodes_config"] - metrics["total_nodes_down"] + ) + ) print("Total Configured Nodes : {0:>8}".format(metrics["total_nodes_config"])) print("") print("Total Allocated CPUs : {0:>8}".format(metrics["total_cpus_alloc"])) print("Total Idle CPUs : {0:>8}".format(metrics["total_cpus_idle"])) print("Total Down CPUs : {0:>8}".format(metrics["total_cpus_down"])) - print("Total Eligible CPUs : {0:>8}".format(metrics["total_cpus_config"] - - metrics["total_cpus_down"])) + print( + "Total Eligible CPUs : {0:>8}".format( + metrics["total_cpus_config"] - metrics["total_cpus_down"] + ) + ) print("Total Configured CPUs : {0:>8}".format(metrics["total_cpus_config"])) - print("Cluster CPU Utilization : {0:>7}%".format(metrics["total_cpus_alloc"] * - 100 / (metrics["total_cpus_config"] - - metrics["total_cpus_down"]))) + print( + "Cluster CPU Utilization : {0:>7}%".format( + metrics["total_cpus_alloc"] + * 100 + / (metrics["total_cpus_config"] - metrics["total_cpus_down"]) + ) + ) print() - print("Total Allocated Memory : {0:>8}".format( - human_readable(metrics["total_memory_alloc"] * 1024 * 1024))) - print("Total Idle Memory : {0:>8}".format( - human_readable(metrics["total_memory_idle"] * 1024 * 1024))) - print("Total Down Memory : {0:>8}".format( - human_readable(metrics["total_memory_down"] * 1024 * 1024))) - print("Total Eligible Memory : {0:>8}".format( - human_readable((metrics["total_memory_config"] - - metrics["total_memory_down"]) * 1024 * 1024))) - print("Total Configured Memory : {0:>8}".format( - human_readable(metrics["total_memory_config"] * 1024 * 1024))) - print("Cluster Memory Utilization : {0:>7}%".format( - metrics["total_memory_alloc"] * 100 / (metrics["total_memory_config"] - - metrics["total_memory_down"]))) + print( + "Total Allocated Memory : {0:>8}".format( + human_readable(metrics["total_memory_alloc"] * 1024 * 1024) + ) + ) + print( + "Total Idle Memory : {0:>8}".format( + human_readable(metrics["total_memory_idle"] * 1024 * 1024) + ) + ) + print( + "Total Down Memory : {0:>8}".format( + human_readable(metrics["total_memory_down"] * 1024 * 1024) + ) + ) + print( + "Total Eligible Memory : {0:>8}".format( + human_readable( + (metrics["total_memory_config"] - metrics["total_memory_down"]) + * 1024 + * 1024 + ) + ) + ) + print( + "Total Configured Memory : {0:>8}".format( + human_readable(metrics["total_memory_config"] * 1024 * 1024) + ) + ) + print( + "Cluster Memory Utilization : {0:>7}%".format( + metrics["total_memory_alloc"] + * 100 + / (metrics["total_memory_config"] - metrics["total_memory_down"]) + ) + ) print() @@ -117,8 +153,8 @@ def display_metrics(metrics): pyslurmnode = pyslurm.node() # Get all node info nodes = pyslurmnode.get() - except ValueError as e: - print("Query failed - {0}").format(e) + except ValueError as value_error: + print("Query failed - {0}".format(value_error)) sys.exit(1) metrics = get_util(nodes) diff --git a/examples/sjobs.py b/examples/sjobs.py index 13eba56c..f6479243 100755 --- a/examples/sjobs.py +++ b/examples/sjobs.py @@ -1,39 +1,44 @@ #!/usr/bin/env python - +""" +List Slurm jobs from certain users +""" from __future__ import print_function -import pyslurm import sys from pwd import getpwnam, getpwuid -from time import gmtime, strftime, sleep -def list_users(job_dict): +import pyslurm + +def list_users(job_dict): + """List Slurm users""" users = [] if job_dict: - for jobid, value in sorted(job_dict.items()): + for _, value in sorted(job_dict.items()): if value["account"] not in users: - users.append(value["account"]) return users + if __name__ == "__main__": try: pyslurmjob = pyslurm.job() jobs = pyslurmjob.get() - except ValueError as e: - print("Job query failed - {0}".format(e.args[0])) + except ValueError as value_error: + print("Job query failed - {0}".format(value_error.args[0])) sys.exit(1) users = list_users(jobs) - delim = "+-------------------------------------------+-----------+------------+---------------+-----------------+--------------+--------------+" + delim = "+-------------------------------------------+-----------+------------+---------------+-----------------+--------------+--------------+" print(delim) - print("| USER (NAME) | CPUS USED | NODES USED | CPU REQUESTED | NODES REQUESTED | JOBS RUNNING | JOBS PENDING |") + print( + "| USER (NAME) | CPUS USED | NODES USED | CPU REQUESTED | NODES REQUESTED | JOBS RUNNING | JOBS PENDING |" + ) print(delim) total_procs_request = 0 @@ -45,11 +50,12 @@ def list_users(job_dict): for user in users: - user_jobs = pyslurmjob.find('account', user) + user_jobs = pyslurmjob.find("account", user) try: gecos = getpwnam(user)[4].split(",")[0] - except: - pass + except Exception as split_error: + print("Couldn't split\n {}".format(gecos)) + sys.exit(1) procs_request = 0 nodes_request = 0 @@ -82,8 +88,28 @@ def list_users(job_dict): total_job_running = total_job_running + running total_job_pending = total_job_pending + pending - print("|{0:>9} ({1:30}) | {2:>9d} | {3:>10d} | {4:>13d} | {5:>15d} | {6:>12d} | {7:>12d} |".format(user.upper(), gecos, procs_used, nodes_used, procs_request, nodes_request, running, pending)) + print( + "|{0:>9} ({1:30}) | {2:>9d} | {3:>10d} | {4:>13d} | {5:>15d} | {6:>12d} | {7:>12d} |".format( + user.upper(), + gecos, + procs_used, + nodes_used, + procs_request, + nodes_request, + running, + pending, + ) + ) print(delim) - print("| TOTAL | {0:>9d} | {1:>10d} | {2:>13d} | {3:>15d} | {4:>12d} | {5:>12d} |".format(total_procs_used, total_nodes_used, total_procs_request, total_nodes_request, total_job_running, total_job_pending)) + print( + "| TOTAL | {0:>9d} | {1:>10d} | {2:>13d} | {3:>15d} | {4:>12d} | {5:>12d} |".format( + total_procs_used, + total_nodes_used, + total_procs_request, + total_nodes_request, + total_job_running, + total_job_pending, + ) + ) print(delim) diff --git a/examples/slurm_ctl.py b/examples/slurm_ctl.py index 45734b6b..bc60117b 100755 --- a/examples/slurm_ctl.py +++ b/examples/slurm_ctl.py @@ -1,20 +1,21 @@ #!/usr/bin/env python - +""" +Manipulate Slurm configuration +""" from __future__ import print_function -import pyslurm import sys +import pyslurm + try: a = pyslurm.config() ctl_dict = a.get() -except ValueError as e: - print("Error - {0}".format(e.args[0])) - sys.exit(-1) +except ValueError as value_error: + print("Error - {0}".format(value_error.args[0])) + sys.exit(1) -# Process the sorted Slurm configuration dictionary - -date_fields = [ 'boot_time', 'last_update' ] +date_fields = ["boot_time", "last_update"] for key in sorted(ctl_dict.items()): if key in date_fields: @@ -25,18 +26,13 @@ ddate = pyslurm.epoch2date(ctl_dict[key]) print("\t{0:<35} : {1}".format(key, ddate)) - elif 'debug_flags' in key: + elif "debug_flags" in key: print("\t{0:<35s} : {1}".format(key[0], pyslurm.get_debug_flags(key[1]))) else: - if 'key_pairs' not in key: + if "key_pairs" not in key: print("\t{0:<35} : {1}".format(key[0], key[1])) if "key_pairs" in ctl_dict: - - print() - print("Additional Information :") - print("------------------------") - print() - - for key in sorted(ctl_dict['key_pairs'].items()): - print("\t{0:<35} : {1}".format(key, ctl_dict['key_pairs'][key])) + print("\nAdditional Information :\n------------------------\n") + for key in sorted(ctl_dict["key_pairs"].items()): + print("\t{0:<35} : {1}".format(key, ctl_dict["key_pairs"][key])) diff --git a/examples/slurm_node_xml.py b/examples/slurm_node_xml.py index 8ef7fc1d..2f88f82f 100755 --- a/examples/slurm_node_xml.py +++ b/examples/slurm_node_xml.py @@ -1,71 +1,83 @@ #!/usr/bin/env python - +""" +Display Slurm node information in XML +""" from __future__ import print_function -from optparse import OptionParser - -import pyslurm -import socket -import time -import pwd -import grp import os +import os.path +import pwd import re +import socket import sys -import os.path +import time +from optparse import OptionParser + +import pyslurm -re_meminfo_parser = re.compile(r'^(?P\S*):\s*(?P\d*)\s*kB') +re_meminfo_parser = re.compile(r"^(?P\S*):\s*(?P\d*)\s*kB") stdout_orig = sys.stdout -def loadavg(host, rrd=""): +def loadavg(host, rrd=""): + """Get Slurm load average""" loadavg = "/proc/loadavg" - load_rrd = '{0}/{1}_loadavg.rrd'.format(rrd, host) + load_rrd = "{0}/{1}_loadavg.rrd".format(rrd, host) try: - f = open(loadavg, 'r').readline().strip() + f = open(loadavg, "r").readline().strip() except IOError: return (-1, -1, -1, -1, -1) data = f.split() avg1min, avg5min, avg15min = map(float, data[:3]) - running, total = map(int, data[3].split('/')) + running, total = map(int, data[3].split("/")) if rrd != "": if not os.path.exists(load_rrd): - os.system("/usr/bin/rrdtool create {0} --step 60 \ + os.system( + "/usr/bin/rrdtool create {0} --step 60 \ DS:loadl1:GAUGE:120:0:U \ DS:loadl5:GAUGE:120:0:U \ DS:loadl15:GAUGE:120:0:U \ RRA:AVERAGE:0.5:1:2160 \ RRA:AVERAGE:0.5:5:2016 \ RRA:AVERAGE:0.5:15:2880 \ - RRA:AVERAGE:0.5:60:8760".format(load_rrd)) + RRA:AVERAGE:0.5:60:8760".format( + load_rrd + ) + ) - os.system("/usr/bin/rrdtool update {0} N:{1}:{2}:{3}".format(load_rrd, avg1min, avg5min, avg15min)) + os.system( + "/usr/bin/rrdtool update {0} N:{1}:{2}:{3}".format( + load_rrd, avg1min, avg5min, avg15min + ) + ) return avg1min, avg5min, avg15min, running, total -def uptime(host, rrd=""): +def uptime(): + """Get Slurm uptime""" uptime = "/proc/uptime" try: - f = open(uptime, 'r').readline().strip() + f = open(uptime, "r").readline().strip() except IOError: - return (-1,-1) + return (-1, -1) data = f.split() return data -def meminfo(host, rrd=""): +def meminfo(): + """Get Slurm memory information""" result = {} meminfo = "/proc/meminfo" try: - f = open(meminfo, 'r').readlines() + f = open(meminfo, "r").readlines() except IOError: return result @@ -73,24 +85,41 @@ def meminfo(host, rrd=""): match = re_meminfo_parser.match(line) if not match: continue - key, value = match.groups(['key', 'value']) + key, value = match.groups(["key", "value"]) result[key] = int(value) return result -if __name__ == '__main__': + +if __name__ == "__main__": usage = "Usage: %prog [options] arg" parser = OptionParser(usage) - parser.add_option("-o", "--stdout", dest="output", - action="store_true", default=False, - help="Write to standard output") - parser.add_option("-d", "--dir", dest="directory", - action="store", default=os.getcwd(), - help="Directory to write data to") - parser.add_option("-r", "--rrd", dest="rrd", default=False, - action="store_true", help="Write rrd data") + parser.add_option( + "-o", + "--stdout", + dest="output", + action="store_true", + default=False, + help="Write to standard output", + ) + parser.add_option( + "-d", + "--dir", + dest="directory", + action="store", + default=os.getcwd(), + help="Directory to write data to", + ) + parser.add_option( + "-r", + "--rrd", + dest="rrd", + default=False, + action="store_true", + help="Write rrd data", + ) (options, args) = parser.parse_args() @@ -102,16 +131,16 @@ def meminfo(host, rrd=""): print("Previous lock file ({0}) exists !".format(lock_file)) sys.exit() else: - open(lock_file,'w').close() + open(lock_file, "w").close() rrd = "" if options.rrd: rrd = options.directory - node_file = r'{0}/{1}.xml'.format(options.directory, my_host) + node_file = r"{0}/{1}.xml".format(options.directory, my_host) if not options.output: stdout_orig = sys.stdout - sys.stdout = open(node_file, 'w') + sys.stdout = open(node_file, "w") now = int(time.time()) sys.stdout.write('\n') @@ -120,23 +149,25 @@ def meminfo(host, rrd=""): sys.stdout.write("\t{0}\n".format(now)) Average = loadavg(my_host, rrd) - sys.stdout.write("\t{0},{1},{2}\n".format(Average[0], Average[1], Average[2])) + sys.stdout.write( + "\t{0},{1},{2}\n".format(Average[0], Average[1], Average[2]) + ) - Uptime = uptime(my_host, rrd) + Uptime = uptime() sys.stdout.write("\t{0},{1}\n".format(Uptime[0], Uptime[1])) - Memory = meminfo(my_host, rrd) - sys.stdout.write("\t{0}\n".format(Memory['MemTotal'])) - sys.stdout.write("\t{0}\n".format(Memory['MemFree'])) - sys.stdout.write("\t{0}\n".format(Memory['Cached'])) - sys.stdout.write("\t{0}\n".format(Memory['Buffers'])) + Memory = meminfo() + sys.stdout.write("\t{0}\n".format(Memory["MemTotal"])) + sys.stdout.write("\t{0}\n".format(Memory["MemFree"])) + sys.stdout.write("\t{0}\n".format(Memory["Cached"])) + sys.stdout.write("\t{0}\n".format(Memory["Buffers"])) a = pyslurm.slurm_load_slurmd_status() if a: for host, data in a.items(): sys.stdout.write("\t\n") for key, value in data.items(): - sys.stdout.write("\t\t<{0}>{1}\n".format(key,value,key)) + sys.stdout.write("\t\t<{0}>{1}\n".format(key, value, key)) sys.stdout.write("\t\n") a = pyslurm.job() @@ -147,27 +178,39 @@ def meminfo(host, rrd=""): for key, value in jobs.items(): jobid = key - if value['job_state'] == "RUNNING": + if value["job_state"] == "RUNNING": userid = pwd.getpwuid(value[4])[0] - nodes = value['alloc_node'].split(',') + nodes = value["alloc_node"].split(",") if my_host in nodes: PiDs[jobid] = [] - a = os.popen('/bin/ps --noheaders -u {0} -o pid,ppid,size,rss,vsize,pcpu,args'.format(userid), 'r') + a = os.popen( + "/bin/ps --noheaders -u {0} -o pid,ppid,size,rss,vsize,pcpu,args".format( + userid + ), + "r", + ) for lines in a: line = lines.split() command = " ".join(line[6:]) - newline = [ line[0], line[1], line[2], line[3], line[4], line[5], command ] + newline = [ + line[0], + line[1], + line[2], + line[3], + line[4], + line[5], + command, + ] pid = int(line[0]) rc, slurm_jobid = pyslurm.slurm_pid2jobid(pid) if rc == 0: - if PiDs.has_key(slurm_jobid): + if slurm_jobid in PiDs: PiDs[slurm_jobid].append(newline) a.close() - if len(PiDs) > 0: - + if PiDs: sys.stdout.write("\t\n") for job, value in PiDs.items(): sys.stdout.write("\t\t\n") @@ -180,7 +223,9 @@ def meminfo(host, rrd=""): sys.stdout.write("\t\t\t\t{0}\n".format(pid[3])) sys.stdout.write("\t\t\t\t{0}\n".format(pid[4])) sys.stdout.write("\t\t\t\t{0}\n".format(pid[5])) - sys.stdout.write("\t\t\t\t\n".format(pid[6])) + sys.stdout.write( + "\t\t\t\t\n".format(pid[6]) + ) sys.stdout.write("\t\t\t\n") sys.stdout.write("\t\t\n") @@ -192,6 +237,6 @@ def meminfo(host, rrd=""): if not options.output: sys.stdout.close() sys.stdout = stdout_orig - os.chmod(node_file, 0644) + os.chmod(node_file, 0o644) os.remove(lock_file) diff --git a/examples/slurm_xml.py b/examples/slurm_xml.py index c994ec37..e4c6b9f3 100755 --- a/examples/slurm_xml.py +++ b/examples/slurm_xml.py @@ -1,45 +1,37 @@ #!/usr/bin/env python - +""" +List Slurm information as XML +""" from __future__ import print_function -import pyslurm import socket -import string -import time -import pwd -import grp import sys -import os -import os.path +import time + +import pyslurm -#hosts = socket.gethostbyaddr(socket.gethostname())[1] my_host = socket.gethostname() if "ernie" not in my_host: sys.exit() now = int(time.time()) -#lock_file = "/var/tmp/slurm_xml.lck" -#if os.path.exists(lock_file): -# sys.exit() -#else: -# open(lock_file, 'w').close() slurm_file = "/tmp/slurm.xml" -xml_file = open(slurm_file,'w') +xml_file = open(slurm_file, "w") -# -# Get the controllers -# +################## +# Get controllers +################## primary, backup = pyslurm.get_controllers() xml_file.write('\n') xml_file.write("\n") xml_file.write("\t{0}\n".format(now)) -# +#################### # XML output of Jobs -# +#################### a = pyslurm.job() jobs = a.get() @@ -47,42 +39,48 @@ xml_file.write("\t\n") for key, value in jobs.items(): - xml_file.write('\t\t\n') + xml_file.write("\t\t\n") xml_file.write("\t\t\t{0}\n".format(key)) for job_key in sorted(value.items()): - xml_file.write("\t\t\t<{0}>{1}\n".format(job_key[0], job_key[1], job_key[0])) + xml_file.write( + "\t\t\t<{0}>{1}\n".format(job_key[0], job_key[1], job_key[0]) + ) b = pyslurm.jobstep(key, 0, 0) steps = b.get() for job, job_step in sorted(steps.items()): - xml_file.write('\t\t\t\n') + xml_file.write("\t\t\t\n") for step in sorted(job_step.items()): xml_file.write("\t\t\t\t{0}\n".format(step)) step_info = pyslurm.slurm_job_step_layout_get(int(job), int(step)) for task in sorted(step_info.items()): - xml_file.write('\t\t\t\t<{0}>{1}\n'.format(task[0], task[1], task[0])) + xml_file.write( + "\t\t\t\t<{0}>{1}\n".format(task[0], task[1], task[0]) + ) - xml_file.write('\t\t\t\n') + xml_file.write("\t\t\t\n") - xml_file.write('\t\t\n') + xml_file.write("\t\t\n") xml_file.write("\t\n") -# +############################ # XML output of Nodes -# +############################# a = pyslurm.node() node_dict = a.get() -xml_file.write( "\t\n") +xml_file.write("\t\n") for key, value in node_dict.items(): - xml_file.write('\t\t\n') + xml_file.write("\t\t\n") xml_file.write("\t\t\t{0}\n".format(key)) for part_key in sorted(value.items()): - xml_file.write("\t\t\t<{0}>{1}\n".format(part_key[0], part_key[1], part_key[0])) + xml_file.write( + "\t\t\t<{0}>{1}\n".format(part_key[0], part_key[1], part_key[0]) + ) if primary and key in primary: xml_file.write("\t\t\tPrimary\n") @@ -91,29 +89,24 @@ else: xml_file.write("\t\t\t\n") - xml_file.write('\t\t\n') -xml_file.write( "\t\n") + xml_file.write("\t\t\n") +xml_file.write("\t\n") -# +########################### # XML output of Partttions -# +########################### a = pyslurm.partition() part_dict = a.get() xml_file.write("\t\n") for key, value in part_dict.items(): - - xml_file.write('\t\t\n') + xml_file.write("\t\t\n") for part_key, part_value in value.items(): xml_file.write("\t\t\t<{0}>{1}\n".format(part_key, part_value, part_key)) - - xml_file.write('\t\t\n') - + xml_file.write("\t\t\n") xml_file.write("\t\n") xml_file.write("\n") xml_file.flush() xml_file.close() - -#os.remove(lock_file) diff --git a/examples/stats.py b/examples/stats.py index 07bb895f..d94b224b 100755 --- a/examples/stats.py +++ b/examples/stats.py @@ -1,23 +1,28 @@ #!/usr/bin/env python - +""" +Display Slurm statistics +""" from __future__ import print_function -def display(stats_dict): +import pyslurm + +def display(stats_dict): + """Format output""" if stats_dict: - print('{0:*^80}'.format(' Slurm Controller Statistics ')) + print("{0:*^80}".format(" Slurm Controller Statistics ")) for key, value in stats_dict.items(): - if key in ['bf_when_last_cycle', 'req_time', 'req_time_start']: + if key in ["bf_when_last_cycle", "req_time", "req_time_start"]: ddate = value if ddate == 0: print("{0:<25} : N/A".format(key)) else: ddate = pyslurm.epoch2date(ddate) print("{0:<25} : {1:<17}".format(key, ddate)) - elif key in ['rpc_user_stats', 'rpc_type_stats']: - label = 'rpc_user_id' - if key == 'rpc_type_stats': - label = 'rpc_type_id' + elif key in ["rpc_user_stats", "rpc_type_stats"]: + label = "rpc_user_id" + if key == "rpc_type_stats": + label = "rpc_type_id" print("{0:<25} :".format(key)) for rpc_key, rpc_val in value.items(): print("\t{0:<12} : {1:<15}".format(label, rpc_key)) @@ -26,20 +31,15 @@ def display(stats_dict): else: print("{0:<25} : {1:<17}".format(key, value)) - print('{0:*^80}'.format('')) + print("{0:*^80}".format("")) else: print("No Stats found !") if __name__ == "__main__": - - import pyslurm - import time - try: stats = pyslurm.statistics() s = stats.get() display(s) - except ValueError as e: - print("Error - {0}".format(e.args[0])) - + except ValueError as value_error: + print("Error - {0}".format(value_error.args[0])) diff --git a/examples/topo_list.py b/examples/topo_list.py index e79f2556..fc230c5f 100755 --- a/examples/topo_list.py +++ b/examples/topo_list.py @@ -1,15 +1,16 @@ #!/usr/bin/env python - +""" +Display Slurm cluster topology +""" from __future__ import print_function import pyslurm -from time import gmtime, strftime try: a = pyslurm.topology() b = a.get() -except ValueError as e: - print("Topology error - {0}".format(e.args[0])) +except ValueError as value_error: + print("Topology error - {0}".format(value_error.args[0])) else: if not b: print("No topology found") diff --git a/examples/triggers_clear.py b/examples/triggers_clear.py index 406f8350..b8d2bfbe 100755 --- a/examples/triggers_clear.py +++ b/examples/triggers_clear.py @@ -1,5 +1,7 @@ #!/usr/bin/env python - +""" +Remove trigger by trigger ID +""" from __future__ import print_function import pyslurm @@ -9,8 +11,7 @@ try: a.clear(TrigID) -except ValueError as e: - print("Unable to clear trigger : {0}".format(e.args[0])) +except ValueError as value_error: + print("Unable to clear trigger : {0}".format(value_error.args[0])) else: print("TriggerID ({0}) cleared".format(TrigID)) - diff --git a/examples/triggers_list.py b/examples/triggers_list.py index f84e8528..09787d47 100755 --- a/examples/triggers_list.py +++ b/examples/triggers_list.py @@ -1,5 +1,7 @@ #!/usr/bin/env python - +""" +List triggers +""" from __future__ import print_function import pyslurm @@ -7,22 +9,30 @@ try: a = pyslurm.trigger() trig_dict = a.get() -except ValueError as e: - print("Trigger error - {0}".format(e.args[0])) +except ValueError as value_error: + print("Trigger error - {0}".format(value_error.args[0])) else: - if len(trig_dict) > 0: + if trig_dict: - print('{0:*^80}'.format('')) + print("{0:*^80}".format("")) for key, value in trig_dict.items(): print("Trigger ID : {0}".format(key)) for part_key in sorted(value.items()): - if 'res_type' in part_key: - print("{0:<25} : {1}".format(part_key, pyslurm.get_trigger_res_type(value[part_key]))) - elif 'trig_type' in part_key: - print("{0:<25} : {1}".format(part_key, pyslurm.get_trigger_type(value[part_key]))) + if "res_type" in part_key: + print( + "{0:<25} : {1}".format( + part_key, pyslurm.get_trigger_res_type(value[part_key]) + ) + ) + elif "trig_type" in part_key: + print( + "{0:<25} : {1}".format( + part_key, pyslurm.get_trigger_type(value[part_key]) + ) + ) else: print("{0:<25} : {1}".format(part_key, value[part_key])) - print('{0:*^80}'.format('')) + print("{0:*^80}".format("")) else: print("No triggers found !") diff --git a/examples/triggers_set.py b/examples/triggers_set.py index 2b1cb1b8..ad6e560b 100755 --- a/examples/triggers_set.py +++ b/examples/triggers_set.py @@ -1,6 +1,8 @@ #!/usr/bin/env python """ +Set a trigger + Trigger ID : 3 offset : 0 program : /tmp/test.sh @@ -51,17 +53,17 @@ import pyslurm trigDict = { - 'res_type': 'node' , - 'res_id': 'makalu', - 'offset': 0, - 'event': 'down', - 'program': '/tmp/test.sh' - } + "res_type": "node", + "res_id": "makalu", + "offset": 0, + "event": "down", + "program": "/tmp/test.sh", +} try: a = pyslurm.trigger() a.set(trigDict) -except ValueError as e: - print("Trigger set failed - {0}".format(e.args[0])) +except ValueError as value_error: + print("Trigger set failed - {0}".format(value_error.args[0])) else: print("Trigger set !")