-3

Is there a way to programmatically check if there are running and/or queued jobs? I'm looking for a script (can be Bash, Python, or any other typical language) that does that and then take some actions if necessary, e.g., shutdown the server (or in my case, an instance in Google Compute Engine). I'd also like to check if there are other users logged in before taking actions. I know the command qstat, but not sure how to use it in a script. Same thing for the command who. I'm using Torque and Ubuntu Server.

Thank you.

EDIT

Given the "down votes", I'll try to give more information. I'd like to do something like the following in pseudo-code:

if "no jobs queued" and "no jobs running" and "no users logged in" then
    shutdown machine
endif

Obviously, the missing part is how to detect, in a script file, the conditions within quotes. The shutdown part isn't important here. I'd appreciate if anyone could give me some pointers or share some ideas. Thanks.

Bruno
  • 1,329
  • 2
  • 15
  • 35

1 Answers1

2
import subprocess
def runCmd(exe):
    p = subprocess.Popen(exe,stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    while True:
        retcode = p.poll()
        line = p.stdout.readline()
        yield line
        if retcode is not None:
            break
def hasRQJob():
    jobs = runCmd('qstat')
    for line in jobs:
        columns = line.split()
        if columns[-2] in ('Q','R'): return True
    return False

The above example shows how to use python to execute shell script and to check whether there is job running or queuing. The function runCmd return the job information like this:

Job id                    Name             User            Time Use S Queue
------------------------- ---------------- --------------- -------- - -----
1773.cluster               CC               Jianhong.Zhou   00:00:00 C MasterStudents 
1774.cluster               RDPSO            Wei.Fang        00:00:00 C PRCI  

Thus, it is easy to judge jobs' status.

The way to check whether there is user logging can reference to 4 Ways to Identify Who is Logged-In on Your Linux System

By the way, the way to execute shell script in python can reference to Calling an external command in Python

Community
  • 1
  • 1
Hooting
  • 1,681
  • 11
  • 20