Search code examples
pythoncmdsubprocesspopenwindows-task-scheduler

Need to get return code from cmd command of the below code using python


This is the code that I want to run in cmd using python and I want it to return data with which I proceed in the program accordingly

SCHTASKS /query /TN TaskName >NUL 2>&1

As you can see, this code probably returns a false value if the TaskName is not found.

I want to get this data i.e: If the task does exist I need to get some error code back and need to get a different return code when it does exist.

I tried using

var=subprocess.Popen(["start", "cmd", "/k", "SCHTASKS /query /TN TaskName >NUL 2>&1"], shell = True)
print var

But this just gives me some object location in the memory presumably. Since this is using the help of cmd it seems to require a different syntax for returning.


Solution

  • don't use start to start in the background, since you won't be able to get return code or output.

    If you just want the return code of the command and hide output/error message, just create a Popen object then wait for task completion:

    p = subprocess.Popen(["SCHTASKS","/query","/TN","TaskName"],stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    return_code = p.wait()
    

    Python 2 doesn't have DEVNULL, so you have to open a null stream manually (How to hide output of subprocess in Python 2.7):

    with open(os.devnull, 'w')  as FNULL:
        p = subprocess.Popen(["SCHTASKS","/query","/TN","TaskName"],stdout=FNULL, stderr=FNULL)
        return_code = p.wait()
    

    if you need to do that in the background, wrap the above code in a python thread. Also:

    • Always pass your command line arguments as lists so the quoting (if needed) is handled automatically
    • Don't use start as you lose control over the process & its return code.
    • Don't use shell=True, since using Popen redirection to DEVNULL is more portable.