Skip to content
Projects

slurm_script_generator.squeue

Attributes

NameDescription
ACTIVE_STATESNo description.
FAILED_JOB_STATESNo description.
JOB_STATESNo description.

Classes

NameDescription
SAcctInterface to SLURM job accounting via sacct.
SAcctJobA single job record from SLURM accounting (sacct).
SQueueInterface to the SLURM job queue via squeue.
SQueueJobA single job entry from the SLURM queue.

Functions

NameDescription
current_userReturn the current OS username (as whoami/$USER would report it).
job_stateReturn the state of a job from SLURM accounting (sacct).
job_statesReturn the states of several jobs from SLURM accounting (sacct).
mainEntry point for the slurm-queue command-line tool.
main_historyEntry point for the slurm-history command-line tool.
main_statsEntry point for the slurm-stats command-line tool.
main_waitEntry point for the slurm-wait command-line tool.
task_statesReturn the states of the tasks of job arrays.

ACTIVE_STATESattributemodule attribute#

ACTIVE_STATES = {'R', 'PD', 'CG', 'CF', 'RQ', 'RS', 'SI', 'SO', 'ST', 'S', 'RH', 'RF'}

FAILED_JOB_STATESattributemodule attribute#

FAILED_JOB_STATES = {
  'BOOT_FAIL',
  'CANCELLED',
  'DEADLINE',
  'FAILED',
  'NODE_FAIL',
  'OUT_OF_MEMORY',
  'PREEMPTED',
  'REVOKED',
  'TIMEOUT'
}

JOB_STATESattributemodule attribute#

JOB_STATES = {
  'BF': 'Boot Fail',
  'CA': 'Cancelled',
  'CD': 'Completed',
  'CF': 'Configuring',
  'CG': 'Completing',
  'DL': 'Deadline',
  'F': 'Failed',
  'NF': 'Node Fail',
  'OOM': 'Out of Memory',
  'PD': 'Pending',
  'PR': 'Preempted',
  'R': 'Running',
  'RD': 'Resv Del Hold',
  'RF': 'Requeue Fed',
  'RH': 'Requeue Hold',
  'RQ': 'Requeued',
  'RS': 'Resizing',
  'RV': 'Revoked',
  'SI': 'Signaling',
  'SE': 'Special Exit',
  'SO': 'Stage Out',
  'ST': 'Stopped',
  'S': 'Suspended',
  'TO': 'Timeout'
}

SAcctclass#

class SAcct(user: Optional[str] = None, days: int = 7, partition: Optional[str] = None, me: bool = False)

Interface to SLURM job accounting via sacct.

Parameters

user : str, optional If given, fetch only jobs for this user. days : int Number of days of history to look back (default: 7). partition : str, optional If given, filter to this partition. me : bool If True, fetch only jobs belonging to the current OS user. Mutually exclusive with user. Defaults to False.

Examples

a = SAcct(user=‘alice’, days=30) a.summary() {‘total’: 42, ‘completed’: 30, ‘failed’: 5, …}

jobsmethod#

def jobs(user: Optional[str] = None, state: Optional[str] = None, partition: Optional[str] = None) -> List[SAcctJob]

Return accounting records matching the given criteria.

jobs_by_partitionmethod#

def jobs_by_partition() -> Dict[str, List[SAcctJob]]

Return a mapping of partition -> list of jobs in that partition.

jobs_by_statemethod#

def jobs_by_state() -> Dict[str, List[SAcctJob]]

Return a mapping of state -> list of jobs in that state.

jobs_by_usermethod#

def jobs_by_user() -> Dict[str, List[SAcctJob]]

Return a mapping of username -> list of their historical jobs.

refreshmethod#

def refresh() -> SAcct

Re-run sacct and update the cached job list.

summarymethod#

def summary() -> dict

Return a summary dict of job counts and CPU usage.

Returns

dict Keys: total, completed, failed, cancelled, timeout, cpu_hours, by_state, users.

SAcctJobclassdataclass#

class SAcctJob(job_id: int, user: str, name: str, state: str, partition: str, num_nodes: int, num_cpus: int, elapsed: str, cpu_time_raw: int, exit_code: str)

A single job record from SLURM accounting (sacct).

cpu_time_rawattributeinstance attribute#

cpu_time_raw: int

elapsedattributeinstance attribute#

elapsed: str

exit_codeattributeinstance attribute#

exit_code: str

job_idattributeinstance attribute#

job_id: int

nameattributeinstance attribute#

name: str

num_cpusattributeinstance attribute#

num_cpus: int

num_nodesattributeinstance attribute#

num_nodes: int

partitionattributeinstance attribute#

partition: str

stateattributeinstance attribute#

state: str

userattributeinstance attribute#

user: str

cpu_hoursproperty#

cpu_hours: float

is_cancelledproperty#

is_cancelled: bool

is_completedproperty#

is_completed: bool

is_failedproperty#

is_failed: bool

is_timeoutproperty#

is_timeout: bool

SQueueclass#

class SQueue(user: Optional[str] = None, partition: Optional[str] = None, me: bool = False)

Interface to the SLURM job queue via squeue.

Parameters

user : str, optional If given, only fetch jobs belonging to this user by default. me : bool If True, fetch only jobs belonging to the current OS user by default. Mutually exclusive with user. Defaults to False.

Examples

q = SQueue() q.summary() {‘total_jobs’: 42, ‘running’: 30, ‘pending’: 12, ‘users’: {…}, ‘by_state’: {…}}

q.wait_until_done(job_name=‘training_*’) q.wait_until_done(job_id=12345) q.wait_until_done(job_id=[12345, 12346]) q.wait_until_done(user=‘alice’)

q.cancel(job_id=12345) q.cancel(job_name=‘training_*’)

cancelmethod#

def cancel(job_name: Optional[str] = None, job_id: Optional[Union[int, str, List[Union[int, str]]]] = None, user: Optional[str] = None, state: Optional[str] = None, partition: Optional[str] = None, verbose: bool = True, me: bool = False) -> List[int]

Cancel all matching jobs with scancel.

Supports glob patterns in job_name (* and ? wildcards). At least one filter argument must be provided, so that an accidental call cannot cancel the whole queue.

Parameters

job_name : str, optional Job name or glob pattern, e.g. 'train_*'. job_id : int, str, or list of int/str, optional A specific job ID, or a list of job IDs, to cancel. user : str, optional Cancel all jobs belonging to this user. me : bool Cancel all jobs belonging to the current OS user. Mutually exclusive with user. Defaults to False. state : str, optional SLURM state code, e.g. 'PD' to cancel only pending jobs. partition : str, optional Partition name to filter by. verbose : bool Print progress messages. Defaults to True.

Returns

list of int The job IDs that were passed to scancel.

Raises

ValueError If no filter is specified. RuntimeError If scancel exits with a non-zero status.

Examples

q = SQueue() q.cancel(job_id=12345) q.cancel(job_name=‘train_*’) q.cancel(user=‘alice’, state=‘PD’)

jobsmethod#

def jobs(job_name: Optional[str] = None, job_id: Optional[Union[int, str, List[Union[int, str]]]] = None, user: Optional[str] = None, state: Optional[str] = None, partition: Optional[str] = None, me: bool = False) -> List[SQueueJob]

Return jobs matching the given criteria.

Parameters

job_name : str, optional Job name or glob pattern (e.g. 'train_*'). job_id : int, str, or list of int/str, optional Exact job ID, or a list of job IDs. user : str, optional Username to filter by. state : str, optional SLURM state code, e.g. 'R' or 'PD'. partition : str, optional Partition name to filter by. me : bool Filter to jobs belonging to the current OS user. Mutually exclusive with user. Defaults to False.

Returns

list of SQueueJob

jobs_by_partitionmethod#

def jobs_by_partition() -> Dict[str, List[SQueueJob]]

Return a mapping of partition name -> list of jobs in that partition.

jobs_by_statemethod#

def jobs_by_state() -> Dict[str, List[SQueueJob]]

Return a mapping of state code -> list of jobs in that state.

jobs_by_usermethod#

def jobs_by_user() -> Dict[str, List[SQueueJob]]

Return a mapping of username -> list of their jobs.

pending_jobsmethod#

def pending_jobs() -> List[SQueueJob]

Return all jobs currently in the PD (Pending) state.

refreshmethod#

def refresh() -> SQueue

Re-run squeue and update the cached job list.

Returns

SQueue self, for chaining.

running_jobsmethod#

def running_jobs() -> List[SQueueJob]

Return all jobs currently in the R (Running) state.

summarymethod#

def summary() -> dict

Return a summary dict with total counts, per-user counts, and per-state counts.

Returns

dict Keys: total_jobs, running, pending, users (dict of user -> job count), by_state (dict of state code -> job count).

usersmethod#

def users() -> List[str]

Return a sorted list of unique users with jobs in the queue.

wait_until_donemethod#

def wait_until_done(job_name: Optional[str] = None, job_id: Optional[Union[int, str, List[Union[int, str]]]] = None, user: Optional[str] = None, poll_interval: float = 30.0, timeout: Optional[float] = None, verbose: bool = True, check: bool = False, me: bool = False) -> Dict[int, Optional[str]]

Block until all matching jobs leave the active queue.

Supports glob patterns in job_name (* and ? wildcards). At least one filter argument must be provided.

Once the jobs are gone the final states are looked up with a single sacct call (see :func:job_states), so the caller learns whether the jobs it waited for actually succeeded.

Parameters

job_name : str, optional Job name or glob pattern, e.g. 'train_*'. job_id : int, str, or list of int/str, optional A specific job ID, or a list of job IDs, to wait for. user : str, optional Wait for all jobs belonging to this user to finish. me : bool Wait for all jobs belonging to the current OS user. Mutually exclusive with user. Defaults to False. poll_interval : float Seconds between queue polls. Defaults to 30. timeout : float, optional Maximum seconds to wait before raising TimeoutError. verbose : bool Print progress messages. Defaults to True. check : bool Raise RuntimeError if any job ended in a state from :data:FAILED_JOB_STATES. Jobs whose state is undetermined (None) never trigger this. Defaults to False.

Returns

dict of int -> (str or None) Final accounting state per job ID that was waited on. A None value means the state could not be determined, not that the job failed.

Raises

ValueError If no filter is specified. TimeoutError If timeout is exceeded before all jobs finish. RuntimeError If check is True and a job ended in a failure state.

Examples

q.wait_until_done(job_id=12345) {12345: ‘COMPLETED’} q.wait_until_done(job_name=‘train_*’, check=True) {12345: ‘COMPLETED’, 12346: ‘COMPLETED’}

SQueueJobclassdataclass#

class SQueueJob(job_id: int, user: str, name: str, state: str, partition: str, num_nodes: int, num_cpus: int, time_used: str, time_limit: str, reason: str, priority: int, submit_time: str = '')

A single job entry from the SLURM queue.

job_idattributeinstance attribute#

job_id: int

nameattributeinstance attribute#

name: str

num_cpusattributeinstance attribute#

num_cpus: int

num_nodesattributeinstance attribute#

num_nodes: int

partitionattributeinstance attribute#

partition: str

priorityattributeinstance attribute#

priority: int

reasonattributeinstance attribute#

reason: str

stateattributeinstance attribute#

state: str

submit_timeattributeclass attributeinstance attribute#

submit_time: str = ''

time_limitattributeinstance attribute#

time_limit: str

time_usedattributeinstance attribute#

time_used: str

userattributeinstance attribute#

user: str

is_activeproperty#

is_active: bool

is_pendingproperty#

is_pending: bool

is_runningproperty#

is_running: bool

state_nameproperty#

state_name: str

submit_datetimeproperty#

submit_datetime: Optional[datetime]

The job’s submission time, or None if squeue didn’t report one.

waiting_secondsproperty#

waiting_seconds: Optional[float]

Seconds elapsed since submission — how long a pending job has waited.

None when the submission time could not be determined.

cancelmethod#

def cancel(verbose: bool = True) -> None

Cancel this specific job with scancel.

Parameters

verbose : bool Print a confirmation message. Defaults to True.

final_statemethod#

def final_state() -> Optional[str]

Return this job’s accounting state via sacct.

See :func:job_state. Returns None when the state cannot be determined; that is not evidence of failure.

wait_until_donemethod#

def wait_until_done(poll_interval: float = 30.0, timeout: Optional[float] = None, verbose: bool = True, check: bool = False) -> Optional[str]

Block until this specific job leaves the active queue.

Parameters

poll_interval : float Seconds between queue polls. Defaults to 30. timeout : float, optional Maximum seconds to wait before raising TimeoutError. verbose : bool Print progress messages. Defaults to True. check : bool Raise RuntimeError if the job ends in a failure state. Defaults to False.

Returns

str or None The job’s final accounting state, or None if undetermined.

current_userfunction#

def current_user() -> str

Return the current OS username (as whoami/$USER would report it).

job_statefunction#

def job_state(job_id: Union[int, str], timeout: float = 30.0) -> Optional[str]

Return the state of a job from SLURM accounting (sacct).

squeue only says whether a job is still in the queue, not how it ended, so this is what distinguishes a crashed run from one that simply wrote no output. States are normalized, e.g. 'CANCELLED by 1234' -> 'CANCELLED'.

Parameters

job_id : int or str The job ID to look up. timeout : float Seconds to wait for sacct before giving up. Defaults to 30.

Returns

str or None The job state ('COMPLETED', 'FAILED', 'RUNNING', …), or None when it cannot be determined — no accounting configured, sacct missing or unresponsive, or the job not yet in the accounting database. A None result is not evidence of failure and callers should not report one.

See Also

job_states : Batch version, one sacct call for many jobs.

Examples

job_state(12345) ‘COMPLETED’

job_statesfunction#

def job_states(job_ids: Union[int, str, List[Union[int, str]]], timeout: float = 30.0) -> Dict[int, Optional[str]]

Return the states of several jobs from SLURM accounting (sacct).

Uses a single sacct call for the whole batch, so waiting on many jobs costs one subprocess rather than one per job. States are normalized, e.g. 'CANCELLED by 1234' -> 'CANCELLED'.

Parameters

job_ids : int, str, or list of int/str The job IDs to look up. timeout : float Seconds to wait for sacct before giving up. Defaults to 30.

Returns

dict of int -> (str or None) One entry per requested job ID, in the order given. The value is None when the state cannot be determined — no accounting configured, sacct missing or unresponsive, or the job not yet in the accounting database. A None value is not evidence of failure and callers should not report one.

Examples

job_states([12345, 12346]) {12345: ‘COMPLETED’, 12346: ‘FAILED’}

mainfunction#

def main() -> None

Entry point for the slurm-queue command-line tool.

Prints the individual-jobs list by default; pass --summary for the per-user summary table instead.

main_historyfunction#

def main_history() -> None

Entry point for the slurm-history command-line tool.

Shows job submission history from accounting records (sacct).

main_statsfunction#

def main_stats() -> None

Entry point for the slurm-stats command-line tool.

Prints partition and state breakdown statistics for the SLURM queue.

main_waitfunction#

def main_wait() -> None

Entry point for the slurm-wait command-line tool.

Blocks until matching jobs leave the active queue.

task_statesfunction#

def task_states(job_ids: Union[int, str, List[Union[int, str]]], timeout: float = 30.0) -> Dict[int, Dict[int, str]]

Return the states of the tasks of job arrays.

:func:job_states folds the tasks of an array into one state per job; this keeps them apart, which is what tells the one failed task of an array from the ninety-nine that finished. The states come from SLURM accounting (one sacct call) and, for the tasks still in the queue, from one squeue call, which is authoritative for those: accounting can lag behind the queue, and on a system without accounting the queue is all there is.

Parameters

job_ids : int, str, or list of int/str The IDs of the array jobs to look up. timeout : float Seconds to wait for sacct and for squeue. Defaults to 30.

Returns

dict of int -> dict of int -> str For each requested job, the state of each task that is known, by task ID: 'PENDING', 'RUNNING', 'COMPLETED', 'FAILED', 'TIMEOUT', … A task that is missing is one whose state cannot be determined (it has left the queue and there is no accounting, or neither command is available); this is not evidence of failure.

See Also

job_states : One state per job, for jobs that are not arrays.

Examples

task_states(12345) {12345: {1: ‘COMPLETED’, 2: ‘FAILED’, 3: ‘RUNNING’, 4: ‘PENDING’}}